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
1 2 3 4 5 6 7 8 9 | 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
1 2 3 4 | EmloyeeRole role = EmloyeeRole.Manager; int roleInterger = (int)role; |
int to enum
Same like above, simply type cast the integer to enum
1 2 3 4 | 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
1 2 3 4 5 | 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
1 2 3 4 | EmloyeeRole role = EmloyeeRole.Manager; string roleString = role.ToString(); |