Coder Perfect

In C#, you can convert a string to an enum.


In C#, what is the most efficient approach to convert a string to an enumeration value?

I’ve got an HTML select tag with enumeration values in it. I want to take the value (which will be in the form of a string) and convert it to the correct enumeration value once the page is published.

In a perfect world, I’d be able to achieve something like this:

StatusEnum MyStatus = StatusEnum.Parse("Active");

That, however, is not a valid code.

Asked by Ben Mills

Solution #1

There is a generic parse method in.NET Core and.NET Framework 4.0:

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

This also contains C#7’s new inline out variables, so the try-parse, conversion to the explicit enum type, and initialization+population of the myStatus variable are all done here.

This is the ideal way if you have access to C#7 and the most recent version of.NET.

It’s a bit unsightly in.NET (till 4 or higher):

StatusEnum MyStatus = (StatusEnum) Enum.Parse(typeof(StatusEnum), "Active", true);

I usually simplify this by saying:

public static T ParseEnum<T>(string value)
    return (T) Enum.Parse(typeof(T), value, true);

Then I’ll be able to:

StatusEnum MyStatus = EnumUtil.ParseEnum<StatusEnum>("Active");

One suggestion in the comments was to add an extension, which is rather straightforward:

public static T ToEnum<T>(this string value)
    return (T) Enum.Parse(typeof(T), value, true);

StatusEnum MyStatus = "Active".ToEnum<StatusEnum>();

Finally, if the string cannot be parsed, you may want to have a default enum:

public static T ToEnum<T>(this string value, T defaultValue) 
    if (string.IsNullOrEmpty(value))
        return defaultValue;

    T result;
    return Enum.TryParse<T>(value, true, out result) ? result : defaultValue;

As a result, this is the decision:

StatusEnum MyStatus = "Active".ToEnum(StatusEnum.None);

However, I would be cautious about adding an extension method like this to string because it will appear on all instances of string, whether or not they contain an enum (thus 1234. ToString(). ToEnum(StatusEnum.None) is acceptable, although it’s illogical.) Unless your entire development team has a thorough understanding of what those extensions accomplish, it’s preferable to avoid cluttering Microsoft’s core classes with extra methods that only apply in very particular scenarios.

Answered by Keith

Solution #2

(.NET 4.0): Enum.TryParseT>(String, T):

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

With C# 7.0’s argument type inlining, it can be simplified even more:

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

Answered by Erwin Mayer

Solution #3

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 at startup and use that to do your conversions.

Answered by McKenzieG1

Solution #4

You’re on the lookout for Enum. Parse.

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

Answered by DavidWhitney

Solution #5

You can now use the following extension methods:

public static T ToEnum<T>(this string value, bool ignoreCase = true)
    return (T) Enum.Parse(typeof (T), value, ignoreCase);

And you can use the following code to call them (FilterType is an enum type):

FilterType filterType = type.ToEnum<FilterType>();

Answered by Foyzul Karim

Post is based on