Pages

Thursday, March 15, 2012

DescriptionAttribute for Enums in C#

Enums provides an efficient way to define a set of named constants that may be assigned to a variable. In C# they can be only number based and have usual naming limitation of not allowing special characters or spaces. Many times we have a requirement where we need to have display user friendly name for Enum value on screen.
public enum ProjectPhase
{
    RequirementsGathering = 1,
    AnalysisDesign = 2,
}
In the above example we need to display more meaningful values on screen. This can be achieved by using the System.ComponentModel and System.Reflection namespace.

Step 1: Use the DescriptionAttribute class to provide the friendly name for enum values.
using System.ComponentModel;
public enum ProjectPhase
{
    [Description("Requirements Gathering")]
     RequirementsGathering = 1,
    [Description("Analysis and Design")]
     AnalysisDesign = 1,
}

Step 2: Create an static class which contains an extension method that extends the Enum type. This extension method GetDecription returns the description of the provided enum value. If there is no description attribute applied on the enum value then the string representation of the enum value is returned.
public static class EnumExtensions
{
    public static string GetDescription(this Enum value)
    {
        string description = string.Empty;
        FieldInfo field = value.GetType().GetField(value.ToString());
        DescriptionAttribute[] attributes = (DescriptionAttribute[])field.GetCustomAttributes(typeof(DescriptionAttribute), false);
        if (attributes.Length > 0)
            description = attributes[0].Description;
        else
             description = value.ToString();
        return description;
     }
}

Step 3: Accessing the Description of enum value
Console.WriteLine(ProjectPhase.Code.GetDescription());

No comments:

Post a Comment