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

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

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

and get all attributes of type DescriptionAttribute

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

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

That’s it.
And as a function 🙂

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
ReadEnumDescription.cs
Version: 1.0

Get description attribute from an enum value. Compile it with csc.exe ReadEnumDescription.cs

Author:Michael
Category:C#
Date:March 23, 2015
1.5 KiB
1012 Downloads
Details...

Leave a Reply Cancel reply