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.
I found that here the case with enum values that have EnumMember value was not considered. So here we go:
And example of that enum:
You can use extension methods now:
And you can call them by the below code (here,
FilterType
is an enum type):BEWARE:
Enum.(Try)Parse()
accepts multiple, comma-separated arguments, and combines them with binary 'or'|
. You cannot disable this and in my opinion you almost never want it.Even if
Three
was not defined,x
would still get int value3
. That's even worse: Enum.Parse() can give you a value that is not even defined for the enum!I would not want to experience the consequences of users, willingly or unwillingly, triggering this behavior.
Additionally, as mentioned by others, performance is less than ideal for large enums, namely linear in the number of possible values.
I suggest the following:
In .NET Core and .NET >4 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.Super simple code using TryParse:
You have to use Enum.Parse to get the object value from Enum, after that you have to change the object value to specific enum value. Casting to enum value can be do by using Convert.ChangeType. Please have a look on following code snippet