Click here to Skip to main content
15,112,866 members
Articles / Programming Languages / C#
Posted 23 Sep 2010

Tagged as


3 bookmarked

TIP: Descriptions for enum values

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


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


About the Author

Jaime Olivares
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 --