[c#] Search for a string in Enum and return the Enum

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

This question is related to c# string enumeration

The answer is


You can cast the int to an enum

(MyColour)2

There is also the option of Enum.Parse

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

All you need is Enum.Parse.


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

(MyColours)Enum.Parse(typeof(MyColours), "red", true); // MyColours.Red
(int)((MyColours)Enum.Parse(typeof(MyColours), "red", true)); // 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.


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.


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


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.


var color =  Enum.Parse<Colors>("Green");

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

You might also want to check out some of the suggestions in this blog post: 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); 

Or check out some of the comments in the same post which talk about using an extension method to achieve similar.


Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to string

How to split a string in two and store it in a field String method cannot be found in a main class method Kotlin - How to correctly concatenate a String Replacing a character from a certain index Remove quotes from String in Python Detect whether a Python string is a number or a letter How does String substring work in Swift How does String.Index work in Swift swift 3.0 Data to String? How to parse JSON string in Typescript

Examples related to enumeration

How to iterate a loop with index and element in Swift Java Enum Methods - return opposite direction enum What does the "map" method do in Ruby? iterating through Enumeration of hastable keys throws NoSuchElementException error Java getting the Enum name given the Enum Value Search for a string in Enum and return the Enum for each loop in Objective-C for accessing NSMutable dictionary (How) can I count the items in an enum? Collection was modified; enumeration operation may not execute in ArrayList Case objects vs Enumerations in Scala