Click here to Skip to main content
Click here to Skip to main content

Enum Display Extension

By , 30 Oct 2011
 

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:

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[^].

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:

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.

   
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:
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)

About the Author

Collin Jasnoch
Engineer
United States United States
Member
No Biography provided

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralMy vote of 5memberA.J.Wegierski14 Jul '12 - 19:13 
Simply great
GeneralRe: My vote of 5memberCollin Jasnoch16 Jul '12 - 3:13 
Thank you Smile | :)
Computers have been intelligent for a long time now. It just so happens that the program writers are about as effective as a room full of monkeys trying to crank out a copy of Hamlet.

GeneralMy vote of 5memberjohannesnestler29 Jun '12 - 12:58 
nice implementation, good one
GeneralReason for my vote of 5 Nice. Can't be used on .Net 2.0, but...memberOshtri Deka29 Feb '12 - 21:05 
Reason for my vote of 5
Nice.
Can't be used on .Net 2.0, but it's nice anyway.
GeneralReason for my vote of 5 Reason? Is simply great!memberFernandaUY21 Dec '11 - 14:01 
Reason for my vote of 5
Reason? Is simply great!
GeneralI'll ask up here, same question: If you use the DescriptionA...membergerm132 Nov '11 - 21:16 
I'll ask up here, same question: If you use the DescriptionAttribute for the enums as part of a web-service, will the description attributes show up in the WSDL?
GeneralReason for my vote of 4 nice little codememberVijay Palaniappan1 Nov '11 - 11:23 
Reason for my vote of 4
nice little code
GeneralReason for my vote of 3 How about localized strings?memberAdrian Cole25 Oct '11 - 16:20 
Reason for my vote of 3
How about localized strings?
GeneralRe: A 3 for that? Ouch. I thought this was really kewl. Granted ...memberCollin Jasnoch26 Oct '11 - 10:05 
A 3 for that? Ouch. I thought this was really kewl. Granted if you have to have localized strings this exact tip will not help you 'entirely', however you could do nothing in the first place.
To me reading from resx files in attributes is a trick itself.
Jim has proposed an alternative for you if you care to see it.
GeneralGreat Enum Examplememberraananv31 Oct '11 - 20:01 
Like!!
GeneralRe: Great Enum ExamplememberCollin Jasnoch1 Nov '11 - 4:06 
Thank you Smile | :)
Computers have been intelligent for a long time now. It just so happens that the program writers are about as effective as a room full of monkeys trying to crank out a copy of Hamlet.

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

Permalink | Advertise | Privacy | Mobile
Web03 | 2.6.130523.1 | Last Updated 30 Oct 2011
Article Copyright 2011 by Collin Jasnoch
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid