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.
So if you had an enum named mood it would look like this:
You can extend the accepted answer with a default value to avoid exceptions:
Then you call it like:
Use
Enum.TryParse<T>(String, T)
(≥ .NET 4.0):It can be simplified even further with C# 7.0's parameter type inlining:
I used class (strongly-typed version of Enum with parsing and performance improvements). I found it on GitHub, and it should work for .NET 3.5 too. It has some memory overhead since it buffers a dictionary.
The blogpost is Enums – Better syntax, improved performance and TryParse in NET 3.5.
And code: https://github.com/damieng/DamienGKit/blob/master/CSharp/DamienG.Library/System/EnumT.cs
Enum.Parse is your friend: