87

How can I parse a string in VB.NET to enum value?

Example I have this enum:

Public Enum Gender
    NotDefined
    Male
    Female
End Enum

how can I convert a string "Male" to the Gender enum's Male value?

4 Answers 4

156
Dim val = DirectCast([Enum].Parse(GetType(Gender), "Male"), Gender)
Sign up to request clarification or add additional context in comments.

4 Comments

what if i don't know the type and wanted to convert generally. in this example you specified Male. i saved the enum value in database and am trying to get it back. in this case i might not know thw actual value that i saved since am converting toString
You should save the related Enum type with the value, say "Namespaces.EnumName". After you can use reflection to get the Type object by name: Dim t = Type.GetType("Namespaces.EnumName") and pass the 't' instead of 'GetType(Gender)'. Also you will have to cast the result value. To do this you must know the specific enum type while writing code.
In .NET 4.0 the syntax is simply: Parse(enumType As System.Type, value As String) As Object
He's asking for the value of the enum, but this snippet just returns an Enum object based from the string. Should be: DirectCast([Enum].Parse(GetType(Gender), "Male"), Integer)
20

See Enum.TryParse.

3 Comments

There is only Parse() method. Not sure where is the Enum.TryParse() method?
@David: Enum.TryParse() is available in .NET 4
correct link, can't edit the answer as it is less then 30 characters: msdn.microsoft.com/en-us/library/dd783499.aspx
5

how can I convert a string "Male" to the Gender enum's Male value?

The accepted solution returns an Enum object. To return the value you want this solution:

dim MyGender as string = "Male"
dim Value as integer
Value = DirectCast([Enum].Parse(GetType(Gender), MyGender), Integer)

Can also do it this way:

value = cInt([enum].Parse(GetType(Gender), MyGender))

Comments

1

If you want the parse to be case insensitive, you can use the following:

[Enum].Parse(Gender, DirectCast(MyGender, String), True)

This will handle dim MyGender as string = "Male" or dim MyGender as string = "male"

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.