This might seems a pretty trivial problem, but every time I've to get an Enum given its name I forgot how to do it, and I've to look for it on Google.
So, is there a better way to remember something you always forget than writing a post about it?
Back to the problem: going from an Enum to its numeric value or its string representation is quite easy:
/* Enum to string */
string stringValue = enumVal.ToString();
/* Enum to numeric value */
int numericVal = (int) enumVal;
And going from a numeric value to the Enum is quite as easy:
/* Numeric value to Enum
int numericVal = 3;
MyEnum enumVal = (MyEnum) numericVal;
But going from the name to the Enum is a bit more complicate... well, if you don't remember the function call: the System.Enum class has a static method (Enum.Parse) that converts a string to the Enumerated type specified:
/* String to Enum */
MyEnum enumVal = (MyEnum) Enum.Parse(typeof(MyEnum), stringValue);
Too bad the need for the cast: they could have implemented a generic version of the Parse method.
I hope I'll remember this function call next time I need it... or at least I know where to look for it.
Technorati tags: C#