What's the best way to convert a string to an enumeration value in C#?
I have an HTML select tag containing the values of an enumeration. When the page is posted, I want to pick up the value (which will be in the form of a string) and convert it to the enumeration value.
In an ideal world, I could do something like this:
StatusEnum MyStatus = StatusEnum.Parse("Active");
but that isn't a valid code.
Parses string to TEnum without try/catch and without TryParse() method from .NET 4.5
We couldn't assume perfectly valid input, and went with this variation of @Keith's answer:
Note that the performance of Enum.Parse() is awful, because it is implemented via reflection. (The same is true of Enum.ToString, which goes the other way.)
If you need to convert strings to Enums in performance-sensitive code, your best bet is to create a
Dictionary<String,YourEnum>
at startup and use that to do your conversions.For performance this might help:
Try this sample:
In this sample you can send every string, and set your
Enum
. If yourEnum
had data that you wanted, return that as yourEnum
type.You're looking for Enum.Parse.