Click here to Skip to main content
15,867,453 members
Articles / Programming Languages / C#
Article

Mapping Text to Enum entries

Rate me:
Please Sign up or sign in to vote.
4.83/5 (64 votes)
6 Jun 2003 226K   2K   91   30
Attaching a description to each entry in an enum.

Sample Image - EnumWithDescription.png

Introduction

While porting old C code to C#, I stumbled across lots of huge arrays which mapped constants to strings. While looking for the C# way of doing this, I discovered custom attributes and reflection.

How is it done?

Append a Description attribute to each enum entry:

C#
private enum MyColors
{
   [Description("yuk!")]       LightGreen    = 0x012020,
   [Description("nice :-)")]   VeryDeepPink  = 0x123456,
   [Description("so what")]    InvisibleGray = 0x456730,
   [Description("no comment")] DeepestRed    = 0xfafafa,
   [Description("I give up")]  PitchBlack    = 0xffffff,
}

To access the description from code, the following function is called:

C#
public static string GetDescription(Enum value)
{
   FieldInfo fi= value.GetType().GetField(value.ToString()); 
   DescriptionAttribute[] attributes = 
         (DescriptionAttribute[])fi.GetCustomAttributes(
         typeof(DescriptionAttribute), false);
   return (attributes.Length>0)?attributes[0].Description:value.ToString();
}

Without the following using declaration, the code will not compile.

C#
using System.ComponentModel;        
using System.Reflection;

Benefits

Instead of having constants and huge arrays all over the code, the above solution keeps declarations and descriptions nicely together.

History

I've only found out by accident that the framework already provides a DescriptionAttribute class.

I built the first version with my own custom attribute and got conflicts when I started using the ComponentModel namespace.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Switzerland Switzerland
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralAutoDoc Pin
Dave Miller4-Feb-04 17:50
Dave Miller4-Feb-04 17:50 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.