- Posted by miketeye on October 9, 2011
Share on FacebookSimple extension class to help use the description attribute with enumeration instances
public static class Extensions
{
public static string ToDescriptionString(this Enum currentEnum)
{
var fi = currentEnum.GetType().GetField(currentEnum.ToString());
var da = (DescriptionAttribute)Attribute.GetCustomAttribute(fi, typeof(DescriptionAttribute));
return da != null ? da.Description : currentEnum.ToString();
}
public static object ParseWithDescriptionAttribute(this System.Enum value, string valueToParse)
{
//Get the Description String Attribute if any exists on the enum value
string descString = value.ToDescriptionString();
if (descString == valueToParse || value.ToString() == valueToParse)
{
return Enum.Parse(value.GetType(), value.ToString());
}
else return null;
}
}