public static class EnumExtensionMethods
{
public static T ParseAsEnumByDescriptionAttribute<T>(this string description) // where T : enum
{
if (string.IsNullOrEmpty(description))
{
throw new ArgumentNullException (description,@"Cannot parse an empty description");
}
Type enumType = typeof(T);
if (!enumType.IsEnum)
{
throw new InvalidOperationException (string.Format("Invalid Enum type{0}",typeof(T)));
}
foreach (T item in Enum.GetValues(typeof(T)))
{
DescriptionAttribute[] attributes = (DescriptionAttribute[])item.GetType().GetField(item.ToString()).GetCustomAttributes(typeof(DescriptionAttribute), false);
if (attributes.Length > 0 && attributes[0].Description.ToUpper() == description.ToUpper())
{
return item;
}
}
throw new InvalidOperationException(string.Format("Couldn't find enum of type {0} with attribute of '{1}'", typeof(T),description));
}
public static string GetDescription(this Enum enumerationValue)
{
DescriptionAttribute[] attributes = (DescriptionAttribute[]) enumerationValue.GetType().GetField(enumerationValue.ToString()).GetCustomAttributes(typeof (DescriptionAttribute), false);
return attributes.Length > 0 ? attributes[0].Description : enumerationValue.ToString();
}
public static EnumDto GetDto(this Enum enumerationValue)
{
return new EnumDto {Value = enumerationValue, Description = GetDescription(enumerationValue)};
}
public static T ToEnum<T>(this string enumerationString)
{
return (T) Enum.Parse(typeof (T), enumerationString);
}