Thursday, June 9, 2011

Cast Int to Enum and vice-versa

Many of times we face a situation where we are to cast integer/string value to Enum or vice-versa

Cast Int To Enum

From a string:
YourEnum foo = (YourEnum) Enum.Parse(typeof(YourEnum), yourString);

From an int:
YourEnum foo = (YourEnum)yourInt;

From number you can also:
YourEnum foo = Enum.ToObject(typeof(YourEnum) , yourInt);

Cast Enum To Int

int something = (int)Question.Role;

Get Enum type as a string: YourEnumName.ItsOption.ToString()

Compiled By Rajesh Rolen

Share This!

No comments:

Powered By Blogger · Designed By Seo Blogger Templates