Microsoft Most Valuable Professional

Chris Pietschmann

An MVP From Wisconsin



C#: Enhance Enums using Extension Methods

Extension Methods are one of the coolest features that have been added in .NET 3.5. I've heard arguments that there is no reason to use them, and the only reason Microsoft added them is to enable the ability to buid LINQ. Well, I do not entirely agree with that statement; in fact, I have found a cool way to use Extension Methods to enhance the System.Enum object since it cannot be inherited. Even though Enum can not be inherited, it can be extended using Extension Methods.

Here's some example code for a simple Enum that has a DescriptionAttribute applied to each of it's values:

public enum LocalizationMarket
{
    [Description("en-US")]
    English = 1,
    [Description("en-ES")]
    Spanish = 2
}

And here's the code to an Extension Method that extends the LocalizationMarket Enum with the ToDescriptionString() method that returns the DescriptionAttributes value:

public static class LocalizationMarketExtensions
{
    public static string ToDescriptionString(this LocalizationMarket val)
    {
        DescriptionAttribute[] attributes = (DescriptionAttribute[])val.GetType().GetField(val.ToString()).GetCustomAttributes(typeof(DescriptionAttribute), false);
        return attributes.Length > 0 ? attributes[0].Description : string.Empty;
    }
}

The usage of this new method is really simple:

LocalizationMarket myLocal = LocalizationMarket.English;
MessageBox.Show( myLocal.ToDescriptionString() ); // this will show "en-US" in the MessageBox that's shown

Now one thing you must remember with using Extension Methods is you may not want to extend the System.Enum Type, but instead just extend the Enums you create only.

Currently rated 4.8 by 4 people

  • Currently 4.75/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Categories: General
Posted by crpietschmann on Tuesday, July 15, 2008 4:38 PM
Permalink | Comments (12) | Post RSSRSS comment feed

Related posts

Comments

Mike gb

Thursday, July 17, 2008 5:56 AM

Mike

This method is very similar to the one I wrote about a while ago:

www.moggoly.me.uk/.../Enum-description-values.aspx

[Wink]

The problem with the method you have posted is that it is tied to the enum type you want to get the description for - the method I posted is generic and will operate on any Enum type.

Chris Pietschmann us

Thursday, July 17, 2008 10:19 AM

Chris Pietschmann

Interesting... I didn't even see your post, and mine is almost identical. It must be a good way to implement it. Smile

And, the reason I'm tying it to the specific enum is to not clutter the api, and possibly confuse someone that it's a method that's part of the .net framework. I'm just mostly using Extension Methods with caution since I'm not sure the the full impact would be of using too many extension methods that would possibly interfere with each other.

Hitesh Pandya us

Thursday, July 17, 2008 6:54 PM

Hitesh Pandya

Reflection is slow, so what is the benefit of using it instead of a switch statement?
Cool idea, but just thinking of performance impact.

Chris Pietschmann us

Thursday, July 17, 2008 10:00 PM

Chris Pietschmann

There are a couple benefits to using reflection within the extension method instead of just using a Switch statement, so long as you need to tweak out as much performance as absolutely possible.

1) Simplicity, you keep the descriptions within the Enumeration, therefore making the code easier to read and change (you only change it in one place).
2) Extensibility, if you make the Extension Method more general and have it work for all Enum types rather than just that specific one, then you have functionality that you can use across your entire application.

The reason I implemented this example to add the ToDescriptionString() method to the LocalizationMarket Enumeration only, is so that you can always refactor your code away from reflection if you need to improve the performance of the ToDescriptionString() method for that specific Enumeration.

Also, remember that the majority of the lag imposed in your application is the time it takes to access your database, this reflection call isn't going to be anywhere near as slow as a database query. And, you can always refactor out the reflection to use a switch statement if you determine that this specfic use of reflection is the entire bottle-neck in your application (and I doubt it will be).

Brenton House us

Thursday, July 17, 2008 10:39 PM

Brenton House

Very similar to my post as well... I guess it's a good idea whose time is here!

weblogs.asp.net/.../...-with-enum-description.aspx

Sam us

Friday, July 18, 2008 2:49 AM

Sam

Interesting... too complex for me though. I usually (try to) go for the simplest possible solution.

ddddddd us

Friday, July 18, 2008 9:50 AM

ddddddd

eeeeeeeeeee

David Kemp gb

Friday, July 18, 2008 6:37 PM

David Kemp

@Hitesh
How do you know it's slower than doing a switch statement? Have you profiled it?
@Sam:
You mean the easiest solution?

weblogs.asp.net

Sunday, July 20, 2008 9:28 PM

pingback

Pingback from weblogs.asp.net

A Cool Channel 9 Webcast covering numerous technology news - Roiy Zysman

rtipton.wordpress.com

Sunday, July 20, 2008 11:14 PM

pingback

Pingback from rtipton.wordpress.com

Weekly Link Post 51 « Rhonda Tipton’s WebLog

Serjo

Sunday, August 24, 2008 6:48 PM

Serjo

here is my version, looks better Smile

public static string ConvertToString(this Enum value)
{
if (value == null)
throw new ArgumentNullException("value");
Type type = value.GetType();
FieldInfo fieldInfo = type.GetField(Enum.GetName(type, value));
var descriptionAttribute =
(DescriptionAttribute) Attribute.GetCustomAttribute(
fieldInfo, typeof (DescriptionAttribute));

if (descriptionAttribute != null)
return descriptionAttribute.Description;
return value.ToString();
}

Alex ch

Wednesday, October 01, 2008 9:58 AM

Alex

@David Kemp

Reflection in general has a big performance impact, there is no need to profile that Wink

Thanks for this article.

Add comment


(Will show your Gravatar icon)  

  Country flag

[b][/b] - [i][/i] - [u][/u]- [quote][/quote]



Live preview

Tuesday, January 06, 2009 8:30 PM

About the author

I'm Chris Pietschmann, go to the About Me page to learn more about me.

Search

Sponsors

Web.Maps.VE - ASP.NET AJAX Virtual Earth Mapping Server Control

Recent comments

Disclaimer


This work is licensed under a Creative Commons Attribution 3.0 United States License, unless explicitly stated otherwise within the posted content.
© Copyright 2004 - 2009 Chris Pietschmann