Description helper for an Enum

Sometimes I wish that I could use an extension methods on a type not just its value. But that’s not happening in .NET 4 or .NET 4.5. So what do we do. Generics to the rescue. But first a bit of context is in order. I work with a Enum’s a lot .Also I  make it a point to have my Enum assigned a Description attribute. Lets consider the Enum code given below.

public enum Directions
    [Description("Points North")]

    [Description("Points South")]

    [Description("Points East")]

    [Description("Points West")]

What I wanted was to have an extension method to get a collection of Description. Well thats not gonna happen.  You can only use and extension type on a vlaue. Getting the description from a single value was simple. Plenty of example online for that . Here is one such example.  They best way is to have a Generic extension method. Here is what I did

public static class Enum
     /// DescriptionList allows descriptive text placed in an Enums.     /// 

    /// The value.
    public static IEnumerable<string> GetDescriptionList()

        var enumValues = Enum.GetValues(typeof(T));
        var descriptionList= new List<string>();

        foreach (var enumValue in enumValues.AsParallel())
            Type type = enumValue.GetType();

            MemberInfo[] memInfo = type.GetMember(enumValue.ToString());

            if (memInfo != null && memInfo.Length > 0)
                object[] attrs = memInfo[0].GetCustomAttributes(typeof(DescriptionAttribute), false);

                if (attrs != null && attrs.Length > 0)

        return descriptionList;

Heres is a sample code on using the utility shown above

internal class Program
        private static void Main()
            var enumDescription = Enum.DescriptionList();

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s