Home
Search
 
What's New
Index
Books
Links
Q & A
Newsletter
Banners
 
Feedback
Tip Jar
 
C# Helper...
 
XML RSS Feed
Follow VBHelper on Twitter
 
 
 
MSDN Visual Basic Community
 
 
 
 
 
 
TitleList the values defined by an Enum in VB .NET
DescriptionThis 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.
KeywordsEnum, reflection
CategoriesVB.NET
 
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.

 
Imports System.Reflection
...
Private Enum ProgrammingLanguage
    VisualBasic
    C
    CPlusPlus
    CPP = CPlusPlus
    CSharp
    Java
End Enum

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 = _
        GetType(ProgrammingLanguage).GetFields

    ' 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 & " = " & _
                CType(field_info.GetValue(Nothing), _
                    Integer) & vbCrLf
        End If
    Next field_info

    ' Display the result.
    txtResults.Text = txt
    txtResults.Select(0, 0)
End Sub
 
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!
 
 
Copyright © 1997-2010 Rocky Mountain Computer Consulting, Inc.   All rights reserved.
  Updated