Author : Admin
Last Modified : 26-Jul-2020
Complexity : Beginner

How to Convert a string to an enum in CSharp?


If you are using .Net framework until 4 there is Enum.Parse() method and if you are using .Net Version > 4 you can use Enum.TryParse() method for converting the string to Enum. Enum.TryParse is much simple implementation rather then Enum.Parse for a string to Enum Conversion.

Let's understand with an example, take an enum of Colors

    enum ColorEnum { Red = 1, Yellow = 2, Black = 3, Orange = 4 };
                    

Before .Net 4

(1) Below code, snippet shows how to convert the string value to an enum.

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

How to use

    ColorEnum MyColor = (ColorEnum) Enum.Parse(typeof(ColorEnum), "Yellow", true);

The last parameter in Enum.Parse() method is boolean to ignore or regard case. Set true to ignore case; false to regard case.

(2) Simplify the way to do this, the extension implementation

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

How to use

    ColorEnum  MyStatus = "Black".ToEnum<ColorEnum>();

.Net > 4

The above two ways can be used in .Net>4 along with these it provides Enum.TryParse() method. Which simplify the code

(3) Below code, snippet shows you how to use Enum.TryParse()

How to use

    ColorEnum MyColor;
    Enum.TryParse("Black", out ColorEnum MyColor);

TryParse method returns true if the parameter was converted successfully; otherwise, false.