Gets the Description attribute from an Enum

public static class EnumEx
    public static T GetValueFromDescription<T>(string description)
        var type = typeof(T);
        if(!type.IsEnum) throw new InvalidOperationException();
        foreach(var field in type.GetFields())
            var attribute = Attribute.GetCustomAttribute(field,
                typeof(DescriptionAttribute)) as DescriptionAttribute;
            if(attribute != null)
                if(attribute.Description == description)
                    return (T)field.GetValue(null);
                if(field.Name == description)
                    return (T)field.GetValue(null);
        throw new ArgumentException("Not found.", "description");
        // or return default(T);


var panda = EnumEx.GetValueFromDescription<Animal>("Giant Panda");

source: stackoverflow


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s