|
|
|||
| H o m e | |||
| G e t V a l u e s a n d G e t N a m e s M e t h o d s o f t h e E n u m C l a s s | |||
|
|
By Michael McIntyre
There are times when you are creating classes where you need to know both the value and name of the enumerators in an Enum. This often comes up when you are deriving a new class from a base class that has one or more protected Enum members.
This article provides code you can use to discover an Enum type’s enumerator values and names. It writes a list of the values and their corresponding names to the console.
Try this code in a button handler on a Windows Form:
' Declare a variable of type "Type" named theEnum. Dim theEnum As Type ' Call the Type class's GetType method ' passing in the name of an Enumerator Type. ' Assign the Type returned by the method to ' the theEnum variable. theEnum = GetType(AnchorStyles)
' Declare a variable of type Integer array named enumValues. ' Call the Enum Class's GetValues method ' to get the enumerator values for an Enum. ' Cast the array returned by the method ' to an array of Integers. ' Assign the array of integers ' to the enumValues variable. Dim enumValues As Integer() = CType([Enum].GetValues(theEnum), Integer())
' Declare a variable of type String array named enumNames. ' Call the Enum Class's GetNames method ' to get the enumerator names for an Enum. ' Assign the array returned by the method ' to the enumNames variable. Dim enumNames As String() = [Enum].GetNames(theEnum)
' Loop through the EnumValues array. Dim i As Integer For i = 0 To enumValues.GetUpperBound(0) ' Write the enumerator and enumerator name to the console. Console.WriteLine(enumValues(i).ToString.PadRight(10) & enumNames(i)) Next
Result:
0 None 1 Top 2 Bottom 4 Left 8 Right
In the code replace AnchorStyles with the name of a different Enum to document that Enum.
To learn more about the GetValues and GetNames methods of the Enum class click here. . |
||
|
Copyright © 2001-2003 aZ Software Developers. All rights reserved. |
|||