I have an enumeration:
public enum MyColours
{
Red,
Green,
Blue,
Yellow,
Fuchsia,
Aqua,
Orange
}
and I have a s
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.