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

Enum Display Extension

Rate me:
Please Sign up or sign in to vote.
4.86/5 (17 votes)
30 Oct 2011CPOL 52.8K   21   11
An extension that allows enums to get their description for display to the UI

Often, we use enums for some selection process (switch statements, etc.), but when we display them to the UI, we need it formatted differently (not camel hump or dash separated).


To start, attributes can be used to store the description, and should be stored in the DescriptionAttribute:


C#
public enum EmployeeType
{
   [DescriptionAttribute("The Big Boss Man")]
   Boss,

   [DescriptionAttribute("Boss's lacky")]
   AdministrativeAssistant,
   
   Janitor,

   [DescriptionAttribute("Everyone Else")]
   StandardEmployee
}

Here, we have defined a simple enum called EmployeeType and added a description attribute to the ones we want to be displayed differently.


Now the interesting part. In case you are unfamiliar with Extensions, here is a link to the MSDN[^].


C#
public static string DisplayString(this Enum value)
{
    //Using reflection to get the field info
    FieldInfo info = value.GetType().GetField(value.ToString());

    //Get the Description Attributes
    DescriptionAttribute[] attributes = (DescriptionAttribute[])info.GetCustomAttributes(typeof(DescriptionAttribute), false);
    
    //Only capture the description attribute if it is a concrete result (i.e. 1 entry)
    if (attributes.Length == 1)
    {
        return attributes[0].Description;
    }
    else //Use the value for display if not concrete result
    {
        return value.ToString();
    }
}

This extension to Enum can then be used like this:


C#
EmployeeType emp = EmplyeeType.Boss;
...
string display = emp.DisplayString();//Retrieves "The Big Boss Man"
string janDisplay = EmployeeType.Janitor.DisplayString(); //retrieves "Janitor"

In addition, if you have the description, you can easily extend the string as well to get back to the actual enum value.


C#
public static object EnumValueOf<t>(this string descriptionOrValue)
{
   //Get all possible values of this enum type
   Array tValues = Enum.GetValues(typeof(T));
 
   //Cycle through all values searching for a match (description or value)
   foreach (Enum val in tValues)
   {
       if (val.DisplayString().Equals(descriptionOrValue) || val.ToString().Equals(descriptionOrValue))
       {
          return val;
       }
    }

    throw new ArgumentException(string.Format("The string value is not of type {0}.", typeof(T).ToString()));
}</t>


Usage:
C#
string display = "The Big Boss Man";
EmployeeType emp = (EmployeeType)display.EnumValueType<employeetype();>

License

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



Comments and Discussions

 
GeneralMy vote of 5 Pin
A.J.Wegierski14-Jul-12 19:13
A.J.Wegierski14-Jul-12 19:13 
GeneralMessage Removed Pin
16-Jul-12 3:13
professionalN_tro_P16-Jul-12 3:13 
GeneralMy vote of 5 Pin
johannesnestler29-Jun-12 12:58
johannesnestler29-Jun-12 12:58 
GeneralReason for my vote of 5 Nice. Can't be used on .Net 2.0, but... Pin
Oshtri Deka29-Feb-12 21:05
professionalOshtri Deka29-Feb-12 21:05 
GeneralReason for my vote of 5 Reason? Is simply great! Pin
FernandoUY21-Dec-11 14:01
professionalFernandoUY21-Dec-11 14:01 
GeneralI'll ask up here, same question: If you use the DescriptionA... Pin
germ132-Nov-11 21:16
germ132-Nov-11 21:16 
GeneralReason for my vote of 4 nice little code Pin
Vijay Palaniappan1-Nov-11 11:23
Vijay Palaniappan1-Nov-11 11:23 
GeneralReason for my vote of 3 How about localized strings? Pin
Adrian Cole25-Oct-11 16:20
Adrian Cole25-Oct-11 16:20 
GeneralMessage Removed Pin
26-Oct-11 10:05
professionalN_tro_P26-Oct-11 10:05 
GeneralGreat Enum Example Pin
raananv31-Oct-11 20:01
raananv31-Oct-11 20:01 
GeneralMessage Removed Pin
1-Nov-11 4:06
professionalN_tro_P1-Nov-11 4:06 

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.