posted 11/22/2011 by Raghav Khunger
In this blog I will show how to cast an int to enum, enum to int and string to enum. Let's make a sample enum:MyEnum.cs
namespace Sample.Console { public enum MyEnum { Item1 = 1, Item2 = 2, Item3 = 3, Item4 = 4, Item5 = 5, } }
1. Int to Enum
int integerValue = 2; MyEnum myenum = (MyEnum)integerValue; //Output: item2
MyEnum myenum = MyEnum.Item3; int integerValue = (int)myenum; //Output: 3
3. String to Enum
string str = "Item4"; MyEnum myenum = (MyEnum)Enum.Parse(typeof(MyEnum), str); //Output: Item4 Enum
What kind of email newsletter would you prefer to receive from CodeAsp.Net?18