To cast a Integer or String to Enum in C# and VB.NET you can use the following snippet.

Sample C#

//from string
MyEnum foo = (MyEnum) Enum.Parse(typeof(MyEnum), inputString);

//from int:
MyEnum foo = (MyEnum)inputInt;

//or also
MyEnum foo = (MyEnum)Enum.ToObject(typeof(MyEnum) , inputInt);

Sample VB.NET

'from string
Dim foo As MyEnum = CType(Enum.Parse(GetType(MyEnum), inputString),MyEnum)

'from int:
Dim foo As MyEnum = CType(inputInt,MyEnum)

'or also
Dim foo As MyEnum = CType(Enum.ToObject(GetType(MyEnum), inputInt),MyEnum)

Attention

  • You can also use TryParse instead of Parse. TryParse returns a boolean that indicates if the parse succeeded or failed.
  • Enum.Parse will NOT work if your code is obfuscated!
  • The “from string” syntax above will actually allow that all numbers passed as String will be accepted without throwing an error! Your Enum will have that value (4711) even though it’s not a valid choice in the Enum itself.
  • You can check if it’s in range using Enum.IsDefined
    if (Enum.IsDefined(typeof(YourEnum), 1)) { //... }

    BUT you can’t use Enum.IsDefined if you use the Flags attribute and the value is a combination of flags for example. Also you should take a look at Validating Arguments Do not use System.Enum.IsDefined(System.Type,System.Object) for enumeration range checks

  • One thought on “How to cast a Integer or String to Enum in C# and VB.NET”

    Leave a Reply