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.
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
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.
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;
}
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);
}
}
}
check out System.Enum.Parse:
enum Colors {Red, Green, Blue}
// your code:
Colors color = (Colors)System.Enum.Parse(typeof(Colors), "Green");