Click here to Skip to main content
15,881,172 members
Articles / Programming Languages / C#
Tip/Trick

TIP: Descriptions for enum values

Rate me:
Please Sign up or sign in to vote.
4.75/5 (4 votes)
23 Sep 2010CPOL 8K   3  
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:

C#
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:

C#
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:

C#
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:
C#
Status st = Status.Inactive;
Console.WriteLine(GetEnumDescription(st));

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Architect
Peru Peru


Computer Electronics professional, Software Architect and senior Windows C++ and C# developer with experience in many other programming languages, platforms and application areas including communications, simulation systems, PACS/DICOM (radiology), GIS, 3D graphics and HTML5-based web applications.
Currently intensively working with Visual Studio and TFS.

Comments and Discussions

 
-- There are no messages in this forum --