|
This post describes how can we convert enum into different data types. These are very
often used operation. This is very simple
to achieve thing. Let take an exmaple
public enum EmloyeeRole
{
None = 0,
Manager = 1,
Admin = 2,
Operator = 3
}
enum to int
To convert a enum to interger simply type cast the enum into integer
EmloyeeRole role = EmloyeeRole.Manager;
int roleInterger = (int)role;
int to enum
Same like above, simply type cast the integer to enum
int roleInterger = 2;
EmloyeeRole role = (EmloyeeRole)roleInterger;
string to enum
If you have string value and you want to type cast that into enum, then you can use
Enum.Parse
string roleString = "Operator";
EmloyeeRole role =
(EmloyeeRole)Enum.Parse(typeof(EmloyeeRole), roleString);
enum to string
This is the simplest one, just use the ToString method of the enum
EmloyeeRole role = EmloyeeRole.Manager;
string roleString = role.ToString();
|