Monday, January 19, 2009

End User Friendly Enum’s – Using an attribute on your enum’s to enable friendly descriptions

Grant Barrington - EnumHelper - Getting a Friendly Description from an Enum

“Wherever possible we use enumerations in our applications. Often the name of the enumeration isn't what you want to print on the screen. It could be because the enumeration is 2 words that have been joined together, or you want the description to start with a number (not that we do this... but you could).

Example

You might have a enumeration for Colours that a user is allowed to select from. The values available for this enumeration may be (hypothetically):

  • Burnt Orange
  • Bright Pink
  • Dark Green
  • Sky Blue

To define this in code, you'd use an enumeration like this:

public enum UserColours
{
BurntOrange = 1,
BrightPink = 2,
DarkGreen = 3,
SkyBlue = 4
}

The Problem

Normally, in an ASP.NET application we'd render an enumeration as a Drop Down List. Problem is we don't want to show "BurntOrange" as a value in the drop down list, we want to show a nice friendly option like "Burnt Orange".

The Solution

We've created a static helper class that uses reflection to get a Description for each member of the enumeration. …

using System.ComponentModel;

namespace Ellington.EnumHelperExamples
{
public enum UserColours
{
[Description("Burnt Orange")]
BurntOrange = 1,

[Description("Bright Pink")]
BrightPink = 2,

[Description("Dark Green")]
DarkGreen = 3,

[Description("Sky Blue")]
SkyBlue = 4
}
}

…”

I’ve seen a number of “friendly enums” posts over the years, but every time I want to actually use one I can never seem to find them… sigh… To “fix the glitch” I’m capturing here one approach for applying a friendly, end user readable, description to an enum.

5 comments:

Anonymous said...

This is a good thing until you need to display your enum in different languages... You should use resources to store strings.

Greg said...

Great point... Thanks

Anonymous said...

Only downside: When you need to obfuscate your assembly you may have problems using this approach.

smnbss said...

why you don't simply parse the Enum, find all the uppercase characters and apply a space before it?
Enums should be quite friendly, if what you need is just a better format, you don't need to apply estra tags. just play with the info the enum already gives you

Unknown said...

smnbss, if you need localisation, you are crewed.