Parse a string to an Enum value in VB.NET

vb.netEnums

vb.net Problem Overview


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?

vb.net Solutions


Solution 1 - vb.net

Dim val = DirectCast([Enum].Parse(GetType(Gender), "Male"), Gender)

Solution 2 - vb.net

Solution 3 - vb.net

> 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))

Solution 4 - vb.net

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"

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionjerbersoftView Question on Stackoverflow
Solution 1 - vb.netKamareyView Answer on Stackoverflow
Solution 2 - vb.netAnton GogolevView Answer on Stackoverflow
Solution 3 - vb.netMax HodgesView Answer on Stackoverflow
Solution 4 - vb.nete.gadView Answer on Stackoverflow