4

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"

neontapir
  • 4,698
  • 3
  • 37
  • 52
Antony Thomas
  • 3,576
  • 2
  • 34
  • 40

3 Answers3

20

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();
}
Nikhil Agrawal
  • 47,018
  • 22
  • 121
  • 208
3

I have an extension method to do just that:

public static string GetDescription(this Enum enumValue)
    {
        //Look for DescriptionAttributes on the enum field
        object[] attr = enumValue.GetType().GetField(enumValue.ToString())
            .GetCustomAttributes(typeof (DescriptionAttribute), false);

        if (attr.Length > 0) // a DescriptionAttribute exists; use it
            return ((DescriptionAttribute) attr[0]).Description;

        //The above code is all you need if you always use DescriptionAttributes;
        //If you don't, the below code will semi-intelligently 
        //"humanize" an UpperCamelCased Enum identifier
        string result = enumValue.ToString();

        //"FooBar" -> "Foo Bar"
        result = Regex.Replace(result, @"([a-z])([A-Z])", "$1 $2");

        //"Foo123" -> "Foo 123"
        result = Regex.Replace(result, @"([A-Za-z])([0-9])", "$1 $2");

        //"123Foo" -> "123 Foo"
        result = Regex.Replace(result, @"([0-9])([A-Za-z])", "$1 $2");

        //"FOOBar" -> "FOO Bar"
        result = Regex.Replace(result, @"(?<!^)(?<! )([A-Z][a-z])", " $1");

        return result;
    }

Usage:

var description = DataType.Alpha.GetDescription(); //"A"

public enum TestEnums
{
   IAmAComplexABCEnumValue,
}

//"I Am A Complex ABC Enum Value"
var complexCamelCasedDescription = TestEnums.IAmAComplexABCEnumValue.GetDescription();
KeithS
  • 70,210
  • 21
  • 112
  • 164
0

I've created a custom generic method to get any attribute value from an enum.

public static class EnumHelper
{
    public static string GetAttributeValueByEnumValue<EnumType, AttributeType>(EnumType value, string attributeProperty = null)
        where EnumType : Enum
        where AttributeType : Attribute
    {
        var enumField = value.GetType().GetField(value.ToString());
        var enumAttributes = enumField?.GetCustomAttributes(typeof(AttributeType), false) as AttributeType[];

        if (enumAttributes == null || !enumAttributes.Any())
            throw new Exception($"Attribute [{typeof(AttributeType).Name}] not found in enum [{typeof(EnumType).Name}] type with value [{value.ToString()}]!");

        var enumAttribute = enumAttributes.First();
        
        var attributeValue = enumAttribute
            .GetType()
            ?.GetProperty(!string.IsNullOrEmpty(attributeProperty) ? attributeProperty : typeof(AttributeType).Name.Replace("Attribute", string.Empty))
            ?.GetValue(enumAttribute);

        if (attributeValue == null)
            throw new Exception("Error reading enum attribute value!");

        return attributeValue.ToString();
    }
}

To use it, simply call it like below:

EnumHelper.GetAttributeValueByEnumValue<EnumLookup, DescriptionAttribute>(enumValue);

You can also provide the attributeProperty name in case of a custom enum, like below:

EnumHelper.GetAttributeValueByEnumValue<EnumLookup, TitleAttribute>(enumValue, "TitleName");

I hope it helps you :)

Sérgio Bueno
  • 99
  • 1
  • 3