How to get enum value by string or int

C#Enums

C# Problem Overview


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.

C# Solutions


Solution 1 - C#

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.

Solution 2 - C#

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>();
    }

Solution 3 - C#

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.

Solution 4 - C#

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.

Solution 5 - C#

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.

Solution 6 - C#

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>();

Solution 7 - C#

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();

Solution 8 - C#

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);
}

Solution 9 - C#

From SQL database get enum like:

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

Solution 10 - C#

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

Solution 11 - C#

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.

Solution 12 - C#

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAbhishek GahloutView Question on Stackoverflow
Solution 1 - C#Kendall FreyView Answer on Stackoverflow
Solution 2 - C#David SpenardView Answer on Stackoverflow
Solution 3 - C#Sriram SakthivelView Answer on Stackoverflow
Solution 4 - C#Abhishek GahloutView Answer on Stackoverflow
Solution 5 - C#AdminBenniView Answer on Stackoverflow
Solution 6 - C#Christoph FinkView Answer on Stackoverflow
Solution 7 - C#huMpty duMptyView Answer on Stackoverflow
Solution 8 - C#user3559224View Answer on Stackoverflow
Solution 9 - C#RFE PetrView Answer on Stackoverflow
Solution 10 - C#Daniel JeongView Answer on Stackoverflow
Solution 11 - C#Mohamad BahmaniView Answer on Stackoverflow
Solution 12 - C#Fabián Plaza ArnauView Answer on Stackoverflow