ExtensionMethod.NET Home of 880 C#, Visual Basic, F# and Javascript extension methods

Enum HasDescription

Multiple ways to check if an enum has description

Source

public static class EnumExtensions
{
    public static string Description(this Enum someEnum)
    {
        var memInfo = someEnum.GetType().GetMember(someEnum.ToString());
 
        if (memInfo != null && memInfo.Length > 0)
        {
            object[] attrs = memInfo[0].GetCustomAttributes(typeof(DescriptionAttribute),false);
 
            if (attrs != null && attrs.Length > 0)
                return ((DescriptionAttribute)attrs[0]).Description;
        }
        return someEnum.ToString();
    }
    public static bool HasDescription(this Enum someEnum)
    {
        return !string.IsNullOrWhiteSpace(someEnum.Description());
    }
    public static bool HasDescription(this Enum someEnum, string expectedDescription)
    {
        return someEnum.Description().Equals(expectedDescription);
    }
    public static bool HasDescription(this Enum someEnum, string expectedDescription, StringComparison comparisionType)
    {
        return someEnum.Description().Equals(expectedDescription, comparisionType);
    }
}

Example

class Program
{
    static void Main()
    {
        const Colors someColor = Colors.Red;
        string description = someColor.Description();
        if (someColor.HasDescription())
        {
            if (someColor.HasDescription("indicates stop", StringComparison.OrdinalIgnoreCase))
            {
                Console.WriteLine("Works");
            }
        }
    }
}
public enum Colors
{
    [Description("Indicates Stop")]
    Red,
    [Description("Indicates Nothing")]
    Blue,
    [Description("Indicates Go")]
    Green
}

Author: Nitin Chaudhari

Submitted on: 23 jun. 2014

Language: C#

Type: Enum

Views: 6774