Over a million developers have joined DZone.

ToDescription Enum Extension Method

·
Provides extension method for retrieving Enum value description values.



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

	/// 
	/// Provides extension method for retrieving Enum value description values.
	/// 
	/// 
	/// 
	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();
	}
}
Topics:

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}