65.9K
CodeProject is changing. Read more.
Home

TIP: Descriptions for enum values

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.75/5 (4 votes)

Sep 23, 2010

CPOL
viewsIcon

8168

A consistent way to add descriptions to enumeration values by reflecting attributes

We can add descriptions to enumeration values and retrieve them at any moment. I will be needed the System.ComponentModel namespace to produce the following arrangement:
public enum Status : int
{
     [Description("User is active with all permissions")]
     Active = 0,
     [Description("User membership has expired")]
     Inactive = 1,
     [Description("User has been suspended for some reason")]
     Suspended = 2
}
The following method will recover the description associated with an specific enum value by doing reflection:
public string GetEnumDescription(object enu)   
{
      return  (enu.GetType().GetField(enu.ToString()).GetCustomAttributes(typeof(DescriptionAttribute), false) as DescriptionAttribute[])[0].Description;
}
This version will prevent any problem is there is no description:
public string GetEnumDescription(object enu)   
{
    try {
      return  (enu.GetType().GetField(enu.ToString()).GetCustomAttributes(typeof(DescriptionAttribute), false) as DescriptionAttribute[])[0].Description;
    }
    catch { return string.Empty; }
}
Here is some test code:
Status st = Status.Inactive;
Console.WriteLine(GetEnumDescription(st));