Get Enum Description - CSharp System

CSharp examples for System:Enum

Description

Get Enum Description

Demo Code


using System.Text;
using System.Reflection;
using System.Linq;
using System.ComponentModel;
using System.Collections.Generic;
using System;/* ww w.j a v a2 s  .  com*/

public class Main{
        public static string GetDescription<T>(this T enumerationValue)
            where T : struct
        {
            var type = enumerationValue.GetType();
            if (!type.IsEnum)
            {
                throw new ArgumentException("EnumerationValue must be of Enum type", "enumerationValue");
            }

            //Tries to find a DescriptionAttribute for a potential friendly name
            //for the enum
            var memberInfo = type.GetMember(enumerationValue.ToString());
            if (memberInfo == null || memberInfo.Length <= 0) return enumerationValue.ToString();
            var attrs = memberInfo[0].GetCustomAttributes(typeof(DescriptionAttribute), false);

            if (attrs != null && attrs.Length > 0)
            {
                //Pull out the description value
                return ((DescriptionAttribute)attrs[0]).Description;
            }
            //If we have no description attribute, just return the ToString of the enum
            return enumerationValue.ToString();

        }
}

Related Tutorials