Click here to Skip to main content
15,881,248 members
Articles / Web Development / ASP.NET
Article

Adding Descriptions to your Enumerations

Rate me:
Please Sign up or sign in to vote.
4.41/5 (21 votes)
17 Apr 2006CPOL1 min read 123.4K   58   8
Describes how to use a [Description] attribute on an enumeration

Introduction

Have you ever wanted to add a more descriptive attribute to your enums? Well, here is one way. Let's take a very simple color based enumeration called MyColors:

C#
using System;
using System.ComponentModel;
using System.Reflection;

public enum MyColors{
   White,
   Red,
   Green
}

Now, as you know, enumerations are represented by numbers (see the docs here).

If you want to associate text, we can do so by using System.ComponentModel.DescriptionAttribute to do this.

C#
using System;
using System.ComponentModel;
using System.Reflection;

public enum MyColors{
   [Description("The Color of my skin")]
   White,
   [Description("Bulls like this color")]
   Red,
   [Description("The color of slime")]
   Green
}

But just associating this attribute with our enum doesn't help. We need a way to access that information too. By using reflection, we can get access to all the attributes for the enumeration. The code below describes a simple accessor that will retrieve the descriptions from each enumeration.

C#
public static string GetDescription(object enumValue, string defDesc){
        FieldInfo fi = enumValue.GetType().GetField(enumValue.ToString());
        
        if (null != fi)
        {
            object[] attrs = fi.GetCustomAttributes(typeof(DescriptionAttribute), true);
            if (attrs != null && attrs.Length > 0)
                return ((DescriptionAttribute)attrs[0]).Description;
        }

        return defDesc;
}

And that is it. Now we can call...

C#
GetDescription(MyColor.Green)

... and we will get back the text from the description. It is just that simple.

Just for fun, let's write a method to get back our enum based on that string. Note: This might be useful for most, but imagine that we define a new attribute called [AssociatedUriAttribute] where we want to associate a URI with our enum that is unique. This opens things up quite a bit. Note: This time we will embed this in a generics based class.

C#
public class EnumUtils<T>
{
    public static T FromDescription(string description){
        Type t = typeof(T);
        foreach (FieldInfo fi in t.GetFields())
        {
            object[] attrs = 
		fi.GetCustomAttributes(typeof(DescriptionAttribute), true);
            if (attrs != null && attrs.Length > 0)
            {
                foreach (DescriptionAttribute attr in attrs)
                {
                    if (attr.Description.Equals(description))
                        return (T)fi.GetValue(null);
                }
            }
        }
        return default(T);
}

In the end, we get a very simple class that looks like this:

C#
using System;
using System.ComponentModel;
using System.Reflection;

/// <summary>
/// enum utilities. 
/// - converts from a [Description(&quot;&quot;)] to an enum value
/// - grabs the [Description(&quot;&quot;)] from an enum value
/// 
/// </summary>
public class EnumUtils<T>
{
    public static string GetDescription(T enumValue, string defDesc){
        
        FieldInfo fi = enumValue.GetType().GetField(enumValue.ToString());
        
        if (null != fi)
        {
            object[] attrs = fi.GetCustomAttributes
					(typeof(DescriptionAttribute), true);
            if (attrs != null && attrs.Length > 0)
                return ((DescriptionAttribute)attrs[0]).Description;
        }

        return defDesc;
    }
    
    public static string GetDescription(T enumValue)
    {
        return GetDescription(enumValue, string.Empty);
    }

    public static T FromDescription(string description){
        Type t = typeof(T);
        foreach (FieldInfo fi in t.GetFields())
        {
            object[] attrs = fi.GetCustomAttributes
					(typeof(DescriptionAttribute), true);
            if (attrs != null && attrs.Length > 0)
            {
                foreach (DescriptionAttribute attr in attrs)
                {
                    if (attr.Description.Equals(description))
                        return (T)fi.GetValue(null);
                }
            }
        }
        return default(T);
    }
}

History

  • 17th April, 2006: Initial post

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Web Developer
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralMy vote of 5 Pin
Аslam Iqbal29-May-13 21:18
professionalАslam Iqbal29-May-13 21:18 
GeneralA tweak Pin
PIEBALDconsult3-Oct-07 14:59
mvePIEBALDconsult3-Oct-07 14:59 
GeneralSeems we reinvented the wheel. Pin
wout de zeeuw13-May-07 0:32
wout de zeeuw13-May-07 0:32 
GeneralIn a utility class Pin
mbowles2013-Nov-06 9:49
mbowles2013-Nov-06 9:49 
Questionhow to make it display in Intellisense Pin
hulinning26-May-06 9:51
hulinning26-May-06 9:51 
Hi,
I wonder how to display description when you browse your objects in the object browser.

I see all Microsoft objects have additional information in the object browser such as Summary

Thanks
GeneralFinally! Pin
Marc Clifton18-Apr-06 1:29
mvaMarc Clifton18-Apr-06 1:29 
GeneralRe: Finally! Pin
skot18-Apr-06 6:44
skot18-Apr-06 6:44 
GeneralRe: Finally! Pin
Richard Deeming28-Apr-06 7:07
mveRichard Deeming28-Apr-06 7:07 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.