196

I have an enumeration:

public enum MyColours
{
    Red,
    Green,
    Blue,
    Yellow,
    Fuchsia,
    Aqua,
    Orange
}

and I have a string:

string colour = "Red";

I want to be able to return:

MyColours.Red

from:

public MyColours GetColour(string colour)

So far i have:

public MyColours GetColours(string colour)
{
    string[] colours = Enum.GetNames(typeof(MyColours));
    int[]    values  = Enum.GetValues(typeof(MyColours));
    int i;
    for(int i = 0; i < colours.Length; i++)
    {
        if(colour.Equals(colours[i], StringComparison.Ordinal)
            break;
    }
    int value = values[i];
    // I know all the information about the matched enumeration
    // but how do i convert this information into returning a
    // MyColour enumeration?
}

As you can see, I'm a bit stuck. Is there anyway to select an enumerator by value. Something like:

MyColour(2) 

would result in

MyColour.Green
2

13 Answers 13

439

check out System.Enum.Parse:


enum Colors {Red, Green, Blue}

// your code:
Colors color = (Colors)System.Enum.Parse(typeof(Colors), "Green");

4
  • 86
    Don't forget you can have it ignore case sensitivity by passing in a third optional parameter to be "true"
    – Aerophilic
    Commented Aug 7, 2013 at 21:37
  • Exactly what I was looking for ! Cheers !
    – Zame
    Commented Oct 20, 2017 at 10:08
  • 11
    @user1531040 Actually, there is an Enum.TryParse.
    – DarLom
    Commented Nov 1, 2017 at 21:14
  • 1
    Note that enum parsing always 'succeeds' if the input is numeric; it just returns the parsed number, which then get cast to the enum's type. So if you want to check if some user input is a valid enum or something else, you should check for numeric content first. Since it returns a valid enum but with a value that may not exist at all in the defined enum names, you can get some really weird problems.
    – Nyerguds
    Commented Mar 3, 2020 at 12:29
24

You can cast the int to an enum

(MyColour)2

There is also the option of Enum.Parse

(MyColour)Enum.Parse(typeof(MyColour), "Red")
0
22

Given the latest and greatest changes to .NET (+ Core) and C# 7, here is the best solution:

var ignoreCase = true;
Enum.TryParse("red", ignoreCase , out MyColours colour);

colour variable can be used within the scope of Enum.TryParse

1
  • what about Enum.Parse<MyColors>("red", true)
    – Berkay
    Commented Oct 13, 2022 at 21:51
5

All you need is Enum.Parse.

0
5
var color =  Enum.Parse<Colors>("Green");
3
  • This doesn't even compile. There is no generic Parse method. Commented Mar 12, 2019 at 0:13
  • 3
    It compiled & worked for me. Maybe it depends on the version you are using? I'm using .NET core 3.1
    – Vinni
    Commented Apr 7, 2020 at 21:06
  • var color = Enum.Parse<Colors>("Green", true); i suppose IgnoreCase had been forgotten.
    – Berkay
    Commented Oct 13, 2022 at 21:55
2

I marked OregonGhost's answer +1, then I tried to use the iteration and realised it wasn't quite right because Enum.GetNames returns strings. You want Enum.GetValues:

public MyColours GetColours(string colour)
{  
   foreach (MyColours mc in Enum.GetValues(typeof(MyColours))) 
   if (mc.ToString() == surveySystem) 
      return mc;

   return MyColors.Default;
}
1

You can use Enum.Parse to get an enum value from the name. You can iterate over all values with Enum.GetNames, and you can just cast an int to an enum to get the enum value from the int value.

Like this, for example:

public MyColours GetColours(string colour)
{
    foreach (MyColours mc in Enum.GetNames(typeof(MyColours))) {
        if (mc.ToString().Contains(colour)) {
            return mc;
        }
    }
    return MyColours.Red; // Default value
}

or:

public MyColours GetColours(string colour)
{
    return (MyColours)Enum.Parse(typeof(MyColours), colour, true); // true = ignoreCase
}

The latter will throw an ArgumentException if the value is not found, you may want to catch it inside the function and return the default value.

1
  • NOTE: It should have been Enum.GetValues, of course, as shown in Colin's answer. Commented Jul 9, 2018 at 12:45
1

Try this method.

public static class Helper
{
  public static T FromStr<T>(string str) where T : struct, System.Enum
    => System.Enum.TryParse<T>(value:str,ignoreCase:true,result:out var result)
    ? result
    : default;
  public static T? FromStrNull<T>(string str) where T : struct, System.Enum
    => System.Enum.TryParse<T>(value: str,ignoreCase: true,result: out var result)
    ? result
    : null;
}

And use it like this

var color = Helper.FromStr<MyColours>("red");
0

As mentioned in previous answers, you can cast directly to the underlying datatype (int -> enum type) or parse (string -> enum type).

but beware - there is no .TryParse for enums, so you WILL need a try/catch block around the parse to catch failures.

1
0
class EnumStringToInt // to search for a string in enum
{
    enum Numbers{one,two,hree};
    static void Main()
    {
        Numbers num = Numbers.one; // converting enum to string
        string str = num.ToString();
        //Console.WriteLine(str);
        string str1 = "four";
        string[] getnames = (string[])Enum.GetNames(typeof(Numbers));
        int[] getnum = (int[])Enum.GetValues(typeof(Numbers));
        try
        {
            for (int i = 0; i <= getnum.Length; i++)
            {
                if (str1.Equals(getnames[i]))
                {
                    Numbers num1 = (Numbers)Enum.Parse(typeof(Numbers), str1);
                    Console.WriteLine("string found:{0}", num1);
                }
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine("Value not found!", ex);
        }
    }
}
2
  • 2
    C# has built-in functionality for this.
    – Artemix
    Commented Nov 28, 2012 at 9:53
  • how is this an answer to the question? look at the other answers for much easier code
    – Firo
    Commented Nov 28, 2012 at 9:55
0

One thing that might be useful to you (besides the already valid/good answers provided so far) is the StringEnum idea provided here

With this you can define your enumerations as classes (the examples are in vb.net):

< StringEnumRegisteredOnly(), DebuggerStepThrough(), ImmutableObject(True)> Public NotInheritable Class eAuthenticationMethod Inherits StringEnumBase(Of eAuthenticationMethod)

Private Sub New(ByVal StrValue As String)
  MyBase.New(StrValue)   
End Sub

< Description("Use User Password Authentication")> Public Shared ReadOnly UsernamePassword As New eAuthenticationMethod("UP")   

< Description("Use Windows Authentication")> Public Shared ReadOnly WindowsAuthentication As New eAuthenticationMethod("W")   

End Class

And now you could use the this class as you would use an enum: eAuthenticationMethod.WindowsAuthentication and this would be essentially like assigning the 'W' the logical value of WindowsAuthentication (inside the enum) and if you were to view this value from a properties window (or something else that uses the System.ComponentModel.Description property) you would get "Use Windows Authentication".

I've been using this for a long time now and it makes the code more clear in intent.

0
(MyColours)Enum.Parse(typeof(MyColours), "red", true); // MyColours.Red
(int)((MyColours)Enum.Parse(typeof(MyColours), "red", true)); // 0
-1

You might also want to check out some of the suggestions in this blog post - reproduced below as the link is now broken: My new little friend, Enum<T>

The post describes a way to create a very simple generic helper class which enables you to avoid the ugly casting syntax inherent with Enum.Parse - instead you end up writing something like this in your code:

MyColours colour = Enum<MyColours>.Parse(stringValue); 

Original blog post content:

I hate ugly code like this:

MyEnum enumValue = (MyEnum) Enum.Parse(typeof (MyEnum), stringValue);

Too many casts for my taste. Here's my answer (and yes it's so simple that I am embarrassed to post it, but just in case you haven't thought of it yet...)

public static class Enum<T>  
{  
    public static T Parse(string value)  
    {  
        return (T) Enum.Parse(typeof (T), value);  
    }  
  
    public static IList<T> GetValues()  
    {  
        IList<T> list = new List<T>();  
        foreach (object value in Enum.GetValues(typeof (T)))  
        {  
            list.Add((T) value);  
        }  
        return list;  
    }  
}  

So the ugliness is converted to

MyEnum enumValue = Enum<MyEnum>.Parse(stringValue);  
1
  • The post link is broken.
    – Machado
    Commented Jul 24, 2018 at 13:58

Your Answer

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

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