0

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?

10
  • I not sure exactly what you're asking. Maybe you could provide some context? Commented May 11, 2020 at 21:13
  • I have declared the enum as said in the question. Now I have received a string value programmatically in my program, say str with value "Myenum" and this value is the name of the enum I have declared. Now I want to use str dynamically to access the values of the enumtype Myenum. Is it possible? Commented May 11, 2020 at 21:22
  • By context, really I'm ask what are you planning on doing with it. Passing an enum name around as a string seems odd, so trying to understand a little bit more about your situation so can give the best advice Commented May 11, 2020 at 21:26
  • It could be as simple as if str = "Myenum" Then.... Commented May 11, 2020 at 21:27
  • I am working with a database where many tables are there, now after running a query I have received a name as "Myenum" which is the name of a table also. Now I want to use this variable of type string to access the values of previously declared enumtype. Commented May 11, 2020 at 22:09

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.