Signup/Sign In
Ask Question
Not satisfied by the Answer? Still looking for a better solution?

Convert a string to an enum 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.
by

3 Answers

rahul07
Use Enum.TryParse<T>(String, T) (? .NET 4.0):

StatusEnum myStatus;
Enum.TryParse("Active", out myStatus);

It can be simplified even further with C# 7.0's parameter type inlining:

Enum.TryParse("Active", out StatusEnum myStatus);
sandhya6gczb
In .NET Core and .NET Framework ?4.0 there is a generic parse method:

Enum.TryParse("Active", out StatusEnum myStatus);

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 the myStatus variable.

If you have access to C#7 and the latest .NET this is the best way.
RoliMishra
You're looking for Enum.Parse.

SomeEnum enum = (SomeEnum)Enum.Parse(typeof(SomeEnum), "EnumValue");

Login / Signup to Answer the Question.