C# Enum.Description() extension method


        ///
        /// Returns the text of the [Description("text")] attribute on an enum. Or null if not found.
        /// 
        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;
        }

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 )

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