Search code examples
c#attributes

How to get the DescriptionAttribute value from an enum member


I have a enum type

public enum DataType:int
    {   
        None = 0,
        [Description("A")]
        Alpha = 1,
        [Description("N")]
        Numeric,
        [Description("AN")]
        AlphaNumeric,
        [Description("D")]
        Date
    }

How do I retrieve the description attribute value of, say, Alpha.

Eg(ideal) : DataType.Alpha.Attribute should give "A"


Solution

  • Use this

    private string GetEnumDescription(Enum value)
    {
        // Get the Description attribute value for the enum value
        FieldInfo fi = value.GetType().GetField(value.ToString());
        DescriptionAttribute[] attributes = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false);
    
        if (attributes.Length > 0)
            return attributes[0].Description;
        else
            return value.ToString();
    }