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:

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

{{ parent.tldr }}

{{ parent.urlSource.name }}