84

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?

Anton Gogolev
  • 113,561
  • 39
  • 200
  • 288
jerbersoft
  • 4,344
  • 9
  • 42
  • 48

4 Answers4

153
Dim val = DirectCast([Enum].Parse(GetType(Gender), "Male"), Gender)
Kamarey
  • 10,832
  • 7
  • 57
  • 70
  • 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 – Smith Jul 09 '11 at 13:50
  • 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. – Kamarey Jul 10 '11 at 14:57
  • 2
    In .NET 4.0 the syntax is simply: `Parse(enumType As System.Type, value As String) As Object` – motto Jul 20 '11 at 16:04
  • 2
    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)` – ChatGPT Oct 18 '12 at 07:52
19

See Enum.TryParse.

Anton Gogolev
  • 113,561
  • 39
  • 200
  • 288
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))
ChatGPT
  • 5,334
  • 12
  • 50
  • 69
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"

e.gad
  • 1,088
  • 19
  • 22