197

How can I get the enum value if I have the enum string or enum int value. eg: If i have an enum as follows:

public enum TestEnum
{
    Value1 = 1,
    Value2 = 2,
    Value3 = 3
}

and in some string variable I have the value "value1" as follows:

string str = "Value1" 

or in some int variable I have the value 2 like

int a = 2;

how can I get the instance of enum ? I want a generic method where I can provide the enum and my input string or int value to get the enum instance.

1

14 Answers 14

383

No, you don't want a generic method. This is much easier:

MyEnum myEnum = (MyEnum)myInt;

MyEnum myEnum = (MyEnum)Enum.Parse(typeof(MyEnum), myString);

I think it will also be faster.

7
  • 1
    This is actually the correct way of doing this. There is no generic way to parse types for the same reason why there is no IParsable interface.
    – Johannes
    May 9, 2014 at 12:38
  • 1
    @Johannes What do you mean by that? There is a generic way, refer my answer and others too. May 9, 2014 at 12:39
  • 1
    @SriramSakthivel The problem the OP describes is solved like KendallFrey showed it. Generic Parsing can not be done - see here: informit.com/blogs/blog.aspx?uk=Why-no-IParseable-interface . Any other solution has no advantage compared to the "onboard" solution of C#. The maximum you can have is an ICanSetFromString<T> where you create and initialise an object to its default(T) and in a next step pass in a representative string. This is close to the answer the OP gave - but it is pointless because usually this is a design issue and a larger point in the system design was missed.
    – Johannes
    May 9, 2014 at 13:54
  • 5
    I think this works now, it's a bit more concise: Enum.Parse<MyEnum>(myString);
    – Phil B
    Feb 28, 2020 at 17:50
  • 2
    One problem with this approach could be (depends on the use case): If myInt has a value that cannot be mapped to an enum value, there is no error and myEnum simply takes the corresponding int value (enum values are ultimately int values).
    – Grimm
    Jul 13, 2021 at 8:50
39

There are numerous ways to do this, but if you want a simple example, this will do. It just needs to be enhanced with necessary defensive coding to check for type safety and invalid parsing, etc.

    /// <summary>
    /// Extension method to return an enum value of type T for the given string.
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="value"></param>
    /// <returns></returns>
    public static T ToEnum<T>(this string value)
    {
        return (T) Enum.Parse(typeof(T), value, true);
    }

    /// <summary>
    /// Extension method to return an enum value of type T for the given int.
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="value"></param>
    /// <returns></returns>
    public static T ToEnum<T>(this int value)
    {
        var name = Enum.GetName(typeof(T), value);
        return name.ToEnum<T>();
    }
27

Could be much simpler if you use TryParse or Parse and ToObject methods.

public static class EnumHelper
{
    public static  T GetEnumValue<T>(string str) where T : struct, IConvertible
    {
        Type enumType = typeof(T);
        if (!enumType.IsEnum)
        {
            throw new Exception("T must be an Enumeration type.");
        }
        return Enum.TryParse(str, true, out T val) ? val : default;
    }

    public static T GetEnumValue<T>(int intValue) where T : struct, IConvertible
    {
        Type enumType = typeof(T);
        if (!enumType.IsEnum)
        {
            throw new Exception("T must be an Enumeration type.");
        }
        
        return (T)Enum.ToObject(enumType, intValue);
    }
}

As noted by @chrfin in comments, you can make it an extension method very easily just by adding this before the parameter type which can be handy.

3
  • 2
    Now also add a this to the parameter and make EnumHelper static and you can use them as extensions too (see my answer, but you have a better/complete code for the rest)... May 9, 2014 at 12:21
  • @chrfin Good idea, but I don't prefer it as it will be popping in intellisense where it is not required when we have namespaces in scope. It will be annoying I guess. May 9, 2014 at 12:26
  • 1
    @chrfin Thanks for the comment, added as a note in my answer. May 9, 2014 at 12:31
13

As suggested by @Phil B in the comments of @Kendall Frey's answer, this can be done quite concisely for strings.

Enum.Parse<MyEnum>(myString);

Adding this since @Kendall Frey's answer gave me a runtime error while @Phil B's revision did not.

7

Following is the method in C# to get the enum value by string

///
/// Method to get enumeration value from string value.
///
///
///

public T GetEnumValue<T>(string str) where T : struct, IConvertible
{
    if (!typeof(T).IsEnum)
    {
        throw new Exception("T must be an Enumeration type.");
    }
    T val = ((T[])Enum.GetValues(typeof(T)))[0];
    if (!string.IsNullOrEmpty(str))
    {
        foreach (T enumValue in (T[])Enum.GetValues(typeof(T)))
        {
            if (enumValue.ToString().ToUpper().Equals(str.ToUpper()))
            {
                val = enumValue;
                break;
            }
        }
    }

    return val;
}

Following is the method in C# to get the enum value by int.

///
/// Method to get enumeration value from int value.
///
///
///

public T GetEnumValue<T>(int intValue) where T : struct, IConvertible
{
    if (!typeof(T).IsEnum)
    {
        throw new Exception("T must be an Enumeration type.");
    }
    T val = ((T[])Enum.GetValues(typeof(T)))[0];

    foreach (T enumValue in (T[])Enum.GetValues(typeof(T)))
    {
        if (Convert.ToInt32(enumValue).Equals(intValue))
        {
            val = enumValue;
            break;
        }             
    }
    return val;
}

If I have an enum as follows:

public enum TestEnum
{
    Value1 = 1,
    Value2 = 2,
    Value3 = 3
}

then I can make use of above methods as

TestEnum reqValue = GetEnumValue<TestEnum>("Value1");  // Output: Value1
TestEnum reqValue2 = GetEnumValue<TestEnum>(2);        // OutPut: Value2

Hope this will help.

2
  • 4
    Can you also please provide reference of where you got this?
    – JonH
    May 9, 2014 at 11:59
  • For this to compile I had to modify the first line to public T GetEnumValue<T>(int intValue) where T : struct, IConvertible Also beware of an extra '}' at the end
    – Avi
    Mar 9, 2015 at 12:50
3

I think you forgot the generic type definition:

public T GetEnumValue<T>(int intValue) where T : struct, IConvertible // <T> added

and you can improve it to be most convinient like e.g.:

public static T ToEnum<T>(this string enumValue) : where T : struct, IConvertible
{
    return (T)Enum.Parse(typeof(T), enumValue);
}

then you can do:

TestEnum reqValue = "Value1".ToEnum<TestEnum>();
3

Try something like this

  public static TestEnum GetMyEnum(this string title)
        {    
            EnumBookType st;
            Enum.TryParse(title, out st);
            return st;          
         }

So you can do

TestEnum en = "Value1".GetMyEnum();
3

Simply try this

It's another way

public enum CaseOriginCode
{
    Web = 0,
    Email = 1,
    Telefoon = 2
}

public void setCaseOriginCode(string CaseOriginCode)
{
    int caseOriginCode = (int)(CaseOriginCode)Enum.Parse(typeof(CaseOriginCode), CaseOriginCode);
}
3

In this moment its possible to use the Enum.TryParse method:

MyType myType;
bool isValidEnum = Enum.TryParse(yourStringValue, out myType);

If "yourStringValue" is not of MyType enum type then isValidEnum is false.

Regards.

2

From SQL database get enum like:

SqlDataReader dr = selectCmd.ExecuteReader();
while (dr.Read()) {
   EnumType et = (EnumType)Enum.Parse(typeof(EnumType), dr.GetString(0));
   ....         
}
0

Here is an example to get string/value

    public enum Suit
    {
        Spades = 0x10,
        Hearts = 0x11,
        Clubs = 0x12,
        Diamonds = 0x13
    }

    private void print_suit()
    {
        foreach (var _suit in Enum.GetValues(typeof(Suit)))
        {
            int suitValue = (byte)(Suit)Enum.Parse(typeof(Suit), _suit.ToString());
            MessageBox.Show(_suit.ToString() + " value is 0x" + suitValue.ToString("X2"));
        }
    }

    Result of Message Boxes
    Spade value is 0x10
    Hearts value is 0x11
    Clubs value is 0x12
    Diamonds value is 0x13
0

You could use following method to do that:

public static Output GetEnumItem<Output, Input>(Input input)
    {
        //Output type checking...
        if (typeof(Output).BaseType != typeof(Enum))
            throw new Exception("Exception message...");

        //Input type checking: string type
        if (typeof(Input) == typeof(string))
            return (Output)Enum.Parse(typeof(Output), (dynamic)input);

        //Input type checking: Integer type
        if (typeof(Input) == typeof(Int16) ||
            typeof(Input) == typeof(Int32) ||
            typeof(Input) == typeof(Int64))

            return (Output)(dynamic)input;

        throw new Exception("Exception message...");
    }

Note:this method only is a sample and you can improve it.

-1
Enum.valueOf(myEnum.class, myString)
-2

Here ise better solution

public static string AsString<T>(this T value) where T : Enum
{
    return Enum.GetName(typeof(T), value);
}

public static T AsEnum<T>(this int value) where T : Enum
{
    if (Enum.IsDefined(typeof(T), value))
    {
        return (T)Enum.ToObject(typeof(T), value);
    }
    else
    {
        throw new ArgumentException($"{value} is not a valid value for enum {typeof(T).Name}");
    }
}
public static int AsInt<T>(this T value) where T : Enum
{
    return (int)(object)value;
}
2
  • 1
    Yiğitcan Ölmez, please don't add Me too as answers. It doesn't actually provide an answer to the question. If you have a different but related question, then ask it (reference this one if it will help provide context). If you are interested in this specific question, you can upvote it, leave a comment, or start a bounty once you have enough reputation. Sep 26 at 9:46
  • is answer enough Sep 26 at 10:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.