Click here to Skip to main content
15,880,392 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 226.4K   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

 
PraiseAdaptation to work with extension methods Pin
Joel Gonzalez22-Mar-21 9:58
Joel Gonzalez22-Mar-21 9:58 
First of all, Thank you !! it was very useful!!
I did this adaptation... hope it can be useful for someone else!
((I'm sorry about my "spanglish" ))


using's:
C#
using System.ComponentModel; //Tag Description
using System.Reflection; // Reflections en Metodos de extensión

add extension methods in some static class, if you want to use it in any Enum, you need to create it with "this Enum value" as parameter, you can also create your extension method for your own enumeration, writing "this [[MyEnumName]] value" as parameter in the extension method.
C#
public static class myClaseEstatica
    {
        public static string GetNameString(this Enum filtro)
        {
            return Enum.GetName(typeof(Enum), filtro);
        }
        public static string GetDescription(this 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();
        }
    }

In your Enum, you shuld only use the Description Tag from ComponentModel with your string correlative message, '[Description("Enum_Element_Text_Value")]
C#
public enum myEnum
    {
        [Description("Enum_Element_Text_Value")]
        Enum_Element,
    }


Finaly, when you need it, you'll only need to call this method from your Enum Value object!!
C#
string valorEnTag = MyEnum.Enum_Element.GetDescription();


Thank's for your help... it makes my day!!
GeneralMy vote of 5 Pin
Lance A. Endres3-Apr-12 7:14
professionalLance A. Endres3-Apr-12 7:14 
GeneralMy vote of 5 Pin
Dorofejev19-Dec-11 23:44
Dorofejev19-Dec-11 23:44 
QuestionHow to use with dataset / tableadapter Pin
Saelen Kenny8-Nov-09 0:01
Saelen Kenny8-Nov-09 0:01 
QuestionQuery regarding description Tag in Enum Pin
NITINKADAM24-Nov-08 5:14
NITINKADAM24-Nov-08 5:14 
GeneralAwesome - thanks! Pin
93522-Jun-07 5:48
93522-Jun-07 5:48 
GeneralDifferent versions for speed improvements Pin
clementgatin12-Mar-07 11:37
clementgatin12-Mar-07 11:37 
GeneralThanks again Pin
Marc Clifton15-Oct-06 3:39
mvaMarc Clifton15-Oct-06 3:39 
GeneralSolution for C / C++ Pin
JimmyO5-May-05 9:56
JimmyO5-May-05 9:56 
GeneralRe: Solution for C / C++ Pin
Uwe Keim10-Apr-06 19:53
sitebuilderUwe Keim10-Apr-06 19:53 
Questionwhy??? Pin
koo918-Jan-05 10:53
koo918-Jan-05 10:53 
AnswerRe: why??? Pin
Reto Ravasio19-Jan-05 8:36
Reto Ravasio19-Jan-05 8:36 
QuestionWhat about Flags? Pin
Spliffy7322-Mar-04 4:22
Spliffy7322-Mar-04 4:22 
AnswerRe: What about Flags? Pin
JSpens14-Aug-07 7:50
JSpens14-Aug-07 7:50 
AnswerRe: What about Flags? Pin
frinkfree11-Nov-08 12:55
frinkfree11-Nov-08 12:55 
GeneralAutoDoc Pin
Dave Miller4-Feb-04 17:50
Dave Miller4-Feb-04 17:50 
GeneralI liked this Pin
Palladino26-Aug-03 2:39
Palladino26-Aug-03 2:39 
QuestionWhat About using the System Enum Pin
vbinfo25-Jun-03 22:10
vbinfo25-Jun-03 22:10 
AnswerRe: What About using the System Enum Pin
Reto Ravasio4-Jul-03 1:04
Reto Ravasio4-Jul-03 1:04 
GeneralRe: What About using the System Enum Pin
vbinfo6-Jul-03 21:05
vbinfo6-Jul-03 21:05 
GeneralRe: What About using the System Enum Pin
Reto Ravasio7-Jul-03 4:47
Reto Ravasio7-Jul-03 4:47 
GeneralRe: What About using the System Enum Pin
devaulr6-Nov-03 2:40
devaulr6-Nov-03 2:40 
GeneralRe: What About using the System Enum Pin
datavalue19-Oct-05 3:06
datavalue19-Oct-05 3:06 
AnswerRe: What About using the System Enum Pin
ConradC1-Feb-05 8:22
ConradC1-Feb-05 8:22 
GeneralMultilingual Pin
Uwe Keim7-Jun-03 21:36
sitebuilderUwe Keim7-Jun-03 21:36 

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.