|Title||List the values defined by an Enum in VB .NET|
|Description||This example shows how to list the values defined by an Enum in VB .NET. It uses reflection to get a list of the values at run time rather than requiring you to hard code the values at design time.|
This program defines an Enum named ProgrammingLanguage. When the form loads, the program uses GetType to get type information about the Enum. It calls the GetFields method to get an array of FieldInfo objects describing the Enum's fields (public variables).
The program checks each FieldInfo object's IsLiteral property to see if it is a literal design time defined value (try commenting this out). It uses the Name property to get the field's name and GetValue to get its numeric value.
Private Enum ProgrammingLanguage
CPP = CPlusPlus
Private Sub Form1_Load(ByVal sender As System.Object, ByVal _
e As System.EventArgs) Handles MyBase.Load
' Enumerate the ProgrammingLanguage fields.
Dim field_infos() As FieldInfo = _
' Loop over the fields.
Dim txt As String = ""
For Each field_info As FieldInfo In field_infos
' See if this is a literal value
' (set at compile time).
If field_info.IsLiteral Then
' List it.
txt &= field_info.Name & " = " & _
Integer) & vbCrLf
' Display the result.
txtResults.Text = txt
The original version of this example created a temporary variable of type ProgrammingLanguage and passed it into the call to GetValue. Max pointed out that you can drop the temporary variable and pass Nothing to this routine instead. GetValue only needs a real object if you want to access values specific to the object. For example, you can use it to read the specific property values of the object. Here we're looking for literal value that don't depend on the object instance so the object isn't necessary. Thanks Max!