Mission Enum Possible
I’m sure you have all been there – thinking “This must be possible” and then the search begins for the answer – you check Google, and all other known sources. Then just seconds before you give up your quest – you find the answer!
Last week I was determined to find a better way to look up the value of an Enum from a string value. For example I have the following Enum
public enum MyEnum
{
MyValue1 = 1,
MyValue2 = 2,
Etc…
};
MyEnum eMyEnum;
What I wanted to do is take a string containing “MyValue2” and assign it to eMyEnum.
After searching Google, my inside c# book and a few other places I was convinced that reflection must have something to do with answer. While you can retrieve info about the Enum setting the value from a string still was elusive.
Finally just before I was about to give up I came across the Enum.Parse method.
Using one line of code you can use Enum.Parse method to set the value of your Enum variable.
Example
eMyEnum = (MyEnum ) Enum.Parse(TypeOf(MyEnum),”Value2”);
Ok let’s have a confession of how many case statements you could replace now that you know about Enum.Parse