C#: Get description attribute from an enum value

Hi,

in this post I will show how to read a description attribute of an enum value by reflection. Let us assume we have a enum linke this

1
2
3
4
5
6
7
8
public enum MetalBands {
    [DescriptionAttribute("This is Metallica from CA")]
    Metallica,
    [DescriptionAttribute("This is Slayer from CA")]
    Slayer,
    [DescriptionAttribute("This is Overkill from NY")]
    Overkill
};


Two steps are necessary
Get the Fieldinfo of the the enum value

1
System.Reflection.FieldInfo oFieldInfo=MetalBands.Metallica.GetType().GetField(MetalBands.Metallica.ToString());

and get all attributes of type DescriptionAttribute

1
DescriptionAttribute[] attributes = (DescriptionAttribute[])oFieldInfo.GetCustomAttributes(typeof(DescriptionAttribute), false);

if an attribute exists print it. We have only one definied , therefore the attribute is at index 0

1
2
3
4
if (attributes.Length > 0)
{
     System.Console.WriteLine(attributes[0].Description);
}

That’s it.
And as a function 🙂

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public static string GetDescription(MetalBands Band)
{
     System.Reflection.FieldInfo oFieldInfo = Band.GetType().GetField(Band.ToString());
     DescriptionAttribute[] attributes = (DescriptionAttribute[])oFieldInfo.GetCustomAttributes(typeof(DescriptionAttribute), false);
     if (attributes.Length > 0)
     {
          return attributes[0].Description;
     }
     else
     {
          return Band.ToString();
     }
}
System.Console.WriteLine(GetDescription(MetalBands.Metallica));

Have fun
Michael

 

Get description attribute from an enum value
Get description attribute from an enum value
ReadEnumDescription.cs
Version: 1.0
1.5 KiB
1076 Downloads
Details...

Leave a Reply