Home > C#

C#: Enhance Enums using Extension Methods

15. July 2008

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.

C# ,

Comments

7/17/2008 11:56:19 PM #
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.
7/18/2008 4:19:20 AM #
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
Hitesh Pandya
7/18/2008 12:54:28 PM #
Reflection is slow, so what is the benefit of using it instead of a switch statement?
Cool idea, but just thinking of performance impact.
7/18/2008 4:00:35 PM #
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).
7/18/2008 4:39:10 PM #
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
7/18/2008 8:49:22 PM #
Interesting... too complex for me though. I usually (try to) go for the simplest possible solution.
ddddddd
ddddddd
7/19/2008 3:50:00 AM #
eeeeeeeeeee
David Kemp
David Kemp
7/19/2008 12:37:47 PM #
@Hitesh
How do you know it's slower than doing a switch statement? Have you profiled it?
@Sam:
You mean the easiest solution?
7/21/2008 3:28:49 PM #
Pingback from weblogs.asp.net

A Cool Channel 9 Webcast covering numerous technology news - Roiy Zysman
7/21/2008 5:14:20 PM #
Pingback from rtipton.wordpress.com

Weekly Link Post 51 « Rhonda Tipton’s WebLog
8/25/2008 12:48:32 PM #
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
Alex
10/2/2008 3:58:16 AM #
@David Kemp

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

Thanks for this article.
5/20/2010 4:42:03 PM #
Pingback from 175.rkwrh.com

Saturn Ls1 Full Opel Vectra, Ls1203 Barcode Scanner