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 corresponding enumeration value.
In an ideal world, I could do something like this:
StatusEnum MyStatus = StatusEnum.Parse("Active");
but that isn't a valid code.
Best Solution
In .NET Core and .NET Framework ≥4.0 there is a generic parse method:
This also includes C#7's new inline
out
variables, so this does the try-parse, conversion to the explicit enum type and initialises+populates themyStatus
variable.If you have access to C#7 and the latest .NET this is the best way.
Original Answer
In .NET it's rather ugly (until 4 or above):
I tend to simplify this with:
Then I can do:
One option suggested in the comments is to add an extension, which is simple enough:
Finally, you may want to have a default enum to use if the string cannot be parsed:
Which makes this the call:
However, I would be careful adding an extension method like this to
string
as (without namespace control) it will appear on all instances ofstring
whether they hold an enum or not (so1234.ToString().ToEnum(StatusEnum.None)
would be valid but nonsensical) . It's often be best to avoid cluttering Microsoft's core classes with extra methods that only apply in very specific contexts unless your entire development team has a very good understanding of what those extensions do.