Friday, July 1, 2016

C# Enum.Description() extension method


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

No comments :