Last Updated: February 25, 2016
·
540
· chadb

Descriptive Enums in C#

Easily add descriptive text to enums in C#:

using System;
using System.ComponentModel;

public enum Genre
{
    [Description("Acid Jazz")]
    AcidJazz,

    Metal,

    [Description("R&B and Soul")]
    RAndBAndSoul
}

You can then access descriptions with an extension method:

using System;
using System.Linq;
using System.Reflection;

public static class Extensions
{
    public static string Description(this Enum value)
    {
        if (value == null)
        {
            throw new ArgumentNullException("value", "value cannot be null.");
        }

        string text = value.ToString();
        string result = text;
        Type type = value.GetType();
        MemberInfo info = type.GetMember(text).FirstOrDefault();

        if (info != null)
        {
            DescriptionAttribute da = info.GetCustomAttributes(
                typeof(DescriptionAttribute), 
                false).FirstOrDefault() as DescriptionAttribute;

            if (da != null)
            {
                result = da.Description;
            }
        }

        return result;
    }
}