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
You can cast the int to an enum
There is also the option of Enum.Parse
Given the latest and greatest changes to .NET (+ Core) and C# 7, here is the best solution:
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 withEnum.GetNames
, and you can just cast an int to an enum to get the enum value from the int value.Like this, for example:
or:
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.
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.
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:Or check out some of the comments in the same post which talk about using an extension method to achieve similar.