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
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
RT @CodeSnippetsNET: How to cast a Integer or String to Enum in C# and #VB .NET http://t.co/t0B9ymsr2P #coding #code #dev #developer #progr…