DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Dennis has posted 5 posts at DZone. View Full User Profile

ToDescription Enum Extension Method

12.01.2009
| 1977 views |
  • submit to reddit
        Provides extension method for retrieving Enum value description values.


public static class EnumExtensionMethods
{
	// Example:
	// [Description("Cents Per Pound")]
	// CentsPerPound = 1,

	/// <summary>
	/// Provides extension method for retrieving Enum value description values.
	/// </summary>
	/// <param name="EnumIn"></param>
	/// <returns></returns>
	public static string ToDescription(this Enum EnumIn)
	{
	    Type type = EnumIn.GetType();
	    MemberInfo[] EnumMemberInfo = type.GetMember(EnumIn.ToString());

	    if (EnumMemberInfo != null && EnumMemberInfo.Length > 0)
	    {
		object[] EnumCustomAttributes = EnumMemberInfo[0].GetCustomAttributes(typeof(DescriptionAttribute), false);
		if (EnumCustomAttributes != null && EnumCustomAttributes.Length > 0)
		{
		    return ((DescriptionAttribute)EnumCustomAttributes[0]).Description;
		}
	    }
	    return EnumIn.ToString();
	}
}