I've used this enum helper from time to time to get an enum value from attributes such as Description and XmlEnumAttribute. Maybe you can find it useful?
public static class EnumEx
{
public static T GetXmlEnumValue(string name)
{
var type = CheckEnum();
var val = (from f in type.GetFields()
let attribute = f.GetCustomAttributes(typeof(System.Xml.Serialization.XmlEnumAttribute), true).FirstOrDefault() as System.Xml.Serialization.XmlEnumAttribute
where attribute != null
&& attribute.Name == name
select (T)f.GetValue(null));
if (val.Count() == 0)
throw new ArgumentException(string.Format("{0} is not a valid XmlEnumAttribute for {1}", name, typeof(T).FullName), "name");
return val.First();
}
public static T GetValueFromDescription(string description)
{
var type = CheckEnum();
var val = (from f in type.GetFields()
let attribute = f.GetCustomAttributes(typeof(System.ComponentModel.DescriptionAttribute), true).FirstOrDefault() as System.ComponentModel.DescriptionAttribute
where attribute != null
&& attribute.Description == description
select (T)f.GetValue(null));
if (val.Count() == 0)
throw new ArgumentException(string.Format("{0} is not a valid description for {1}", description, typeof(T).FullName), "description");
return val.First();
}
private static Type CheckEnum()
{
var type = typeof(T);
if (type.IsEnum == false)
throw new InvalidOperationException(string.Format("{0} is not an enum", typeof(T)));
return type;
}
}
