Saturday, July 3, 2010

Enum to Description

Recently we had an issue with maintaining enum descriptions in our project. The problem was descriptions duplicated several places in codebase and when it came to modify descriptions we had to modify the description everywhere. From the maintainability perspective this not a good practice and we came up with a solution by using the coolest feature Extensions methods that comes with the .NET 3.5. Following is the sample code of the solution.
using System;
using System.ComponentModel;
using System.Reflection;

namespace EnumToDescriptionTest
{
    public static class EnumExtensions
    {
        // Extension method to get the enum description.
        public static string ToDescription(this Enum val)
        {
            Type type = val.GetType();

            string name = Enum.GetName(type, val);
            FieldInfo field = type.GetField(name);

            // Check for the Description Attribute.
            DescriptionAttribute[] attributes = (DescriptionAttribute[])field.GetCustomAttributes(
                                                typeof(DescriptionAttribute), false);

            return attributes.Length > 0 ? attributes[0].Description : name;
        }
    }

    class Program
    {
        // Define the enum with description.
        public enum UserMode
        {
            [Description("Add User")]
            Add = 0,
            [Description("Update User")]
            Update = 1,
            [Description("Delete User")]
            Delete = 2
        }

        static void Main(string[] args)
        {
            // Get the enum description.
            Console.WriteLine(UserMode.Add.ToDescription());
            Console.ReadLine();
        }
    }
}

No comments: