Meghdut Saha
Meghdut Saha

Reputation: 85

How to get the enum type from a string in vb.net

I have declared a enum as below:

Public Enum Myenum
    val1 = 0
    val2 = 1
End Enum

Now I have a variable with the name

Dim str As String = "Myenum"

How can I use variable str to access the values of the enum?

Upvotes: 0

Views: 388

Answers (1)

Jimi
Jimi

Reputation: 32223

If the scope where the Enumerator is defined is a class object, you can use the current instance type to get a member corresponding to the Enumerator type name, using GetType().GetMember():

If the Enumerator(s) may not be public, specify BindingFlags that allow to include non-public members. Add BindingFlags.IgnoreCase if needed.

Imports System.Reflection

Dim enumTypeName = "MyEnum"

Dim flags = BindingFlags.Instance Or BindingFlags.NonPublic Or 
            BindingFlags.Public Or BindingFlags.IgnoreCase

Dim myEnumTypeInfo = Me.GetType().GetMember(enumTypeName, flags).FirstOrDefault()
If myEnumTypeInfo IsNot Nothing AndAlso Type.GetType(myEnumTypeInfo.ToString()).IsEnum Then
    Dim myEnumValues = Type.GetType(myEnumTypeInfo.ToString()).GetEnumValues()
    '[...]
End If

If the enumerator type is defined in a wider scope, you can use Assembly.GetExecutingAssembly() and get the type from DefinedTypes:

Dim myEnumType = Assembly.GetExecutingAssembly().
                 DefinedTypes.FirstOrDefault(Function(t) t.Name = enumTypeName)

If myEnumType IsNot Nothing AndAlso myEnumType.IsEnum Then
    Dim myEnumValues = myEnumType.GetEnumValues()
    '[...]
End If

Upvotes: 1

Related Questions