Casting C# Enums

It’s a short memo how to cast enum to int or string and vice versa.

1. Enum -> int
int value = (int)myEnum;

2. Enum -> string
string name = myEnum.ToString();

3. Int -> Enum
myEnum = (MyEnum)2;

4. String -> Enum
myEnum = (MyEnum) Enum.Parse(typeof(MyEnum), stateName);
bool parseSuccess = Enum.TryParse(stateName, out myEnum);


Leave a Reply

Your email address will not be published. Required fields are marked *