C# Enum.Description() extension method

        /// 
/// Returns the text of the [Description("text")] attribute on an enum. Or null if not found.
///

///
///
[ CanBeNull ]
public static String Description( this Enum element ) {
var type = element.GetType();

var memberInfo = type.GetMember( element.ToString() );

if ( !memberInfo.Any() ) {
return null;
}
var attributes = memberInfo[ 0 ].GetCustomAttributes( typeof( DescriptionAttribute ), false );

return attributes.Any() ? ( attributes[ 0 ] as DescriptionAttribute )?.Description : null;
}
Advertisements

Author: Protiguous

C# Software Developer, Father, and seeker of Truth.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s