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 names of the values defined by an arbitrary Enum in VB .NET
DescriptionThis example shows how to List the names of the values defined by an arbitrary 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
 
The ListEnumNames function takes a parameter giving the type of an Enum. It calls the type's 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) and adds the literal fields' names to the result array.

 
Imports System.Reflection
...
' Return a list of an enumerated type's value names.
Public Function ListEnumNames(ByVal enum_type As Type) As _
    String()
    ' Enumerate the Enum's fields.
    Dim field_infos() As FieldInfo = enum_type.GetFields

    ' Loop over the fields.
    Dim results() As String
    Dim max_result As Integer = -1
    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
            ' Add it.
            max_result += 1
            ReDim Preserve results(max_result)
            results(max_result) = field_info.Name
        End If
    Next field_info

    Return results
End Function
 
 
Copyright © 1997-2010 Rocky Mountain Computer Consulting, Inc.   All rights reserved.
  Updated