Get an Enum value from a string
I love to use enumerated datatypes for programming. This code snippet is really useful for getting an enum value from it's name rather than it's integer index.
The original article was here: http://blog.paranoidferret.com/index.php/2007/09/17/csharp-snippet-tutorial-how-to-get-an-enum-from-a-string/
UPDATE - I've updated the code to check if the Enum contains the value first
private T StringToEnum<T>(string name)
{
string[] names = Enum.GetNames(typeof(T));
if (((IList)names).Contains(name))
{
return (T)Enum.Parse(typeof(T), name);
}
else return default(T);
}
{
return (T)Enum.Parse(typeof(T), name);
}
Examples:
public enum DaysOfWeek
{
Monday,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday,
Sunday
}
public enum MonthsInYear
{
January,
February,
March,
April,
May,
June,
July,
August,
September,
October,
November,
December
}
DaysOfWeek d = StringToEnum<DaysOfWeek>("Monday");
//d is now DaysOfWeek.Monday
MonthsInYear m = StringToEnum<MonthsInYear>("January");
//m is now MonthsInYear.January
//throws an ArgumentException
//Requested value "Katillsday" was not found.
StringToEnum<DaysOfWeek>("Katillsday");
http://blog.paranoidferret.com/index.php/2007/09/17/csharp-snippet-tutorial-how-to-get-an-enum-from-a-string/