The Orbit Notebook Software Architecture, Development and Design Thoughts

31Dec/110

" href="http://blueorbitsoftware.com/blog/?p=168" rel="bookmark">Make your enumeration values friendlier with this Enum Description extension method

I like to DataBind. In fact, I love to DataBind. It makes my job as a programmer extremely easy, and gives me the ability to write less code with the payoff of faster performance.  Sold.

Typically, when writing ASP.NET websites, I'm using data binding to attach a collection to a control, let's say a DropDownList. In most cases, my data source is a database and the values that I show in my DropDownList are from a Description (or other user-friendly-type) column.

But what happens when I want to data bind to an enumeration? Doesn't seem like a big deal, until you realize that many enumerations contain multi-word values. For example, an enumeration of colors can be easily data bound to a DropDownList and looks relatively clean when your color has a simple one-word name:

But what happens when you have a color that has a multiple-word name, like this:

Gross.  That just isn't acceptable.

As you know, .NET enumerations allow for a Description attribute, and this thing is a lifesaver. It allows you to attach pretty and user-friendly text to an enumeration, as a description. For instance:

Okay, cool.  So we've attached some user-friendly descriptions to our enumerations.  How do we get those descriptions out of the enum, for our data binding?

This is where extension methods come in to play.  There is an extension method that's been floating around the interwebs for a while that allows you to generically pass your enumeration type, while returning you the description of the value you're in need of.  Here's the snippet and some comments that we'll use in our example, below.

/// <summary>
/// Allows a description "friendly value" to be retrieved for an enumeration.
/// i.e.;
///
/// [Description("Built-In Microwave")]
/// BuiltInMicrowave = 9
///
/// </summary>
public static class Enum<T>
{
   public static string Description(T value)
   {
     DescriptionAttribute[] da = (DescriptionAttribute[])(typeof(T).GetField(value.ToString()).GetCustomAttributes(typeof(DescriptionAttribute), false));
     return da.Length > 0 ? da[0].Description : value.ToString();
   }
}

In essence, you qualify the Enum object with the type of enumeration, and then you pass the enumeration number to the Description method.  Using the "Built-in Microwave" example in our code comments, you would call this extension method like so:

string friendlyDescription = Enum<ApplianceType>.Description(9);

This will return the friendly description, "Built-In Microwave" which you can pull directly into a List, Dictionary, or IEnumeration, and quickly databind into your page controls.

Comments (0) Trackbacks (0)

No comments yet.


Leave a comment

(required)

No trackbacks yet.