I’m going to show how to get the value from the Description attribute on each enum.
We have the following enum as an example
public enum MonthOfYear { [Description("First month of the year")] January, [Description("Second month of the year")] February, [Description("Third month of the year")] March // ... and so on }
If you use MonthOfYear.January or MonthOfYear.January.ToString(), you’ll get the string value “January”.
To get the value in the Description attribute, you need to first check if the field has any Description attribute and then get its description. So let’s look at the extension method to do this.
public static class EnumExtension { public static string GetDescription(this Enum value) { var type = value.GetType(); var name = Enum.GetName(type, value); if (name != null) { var field = type.GetField(name); if (field != null) { var attr = Attribute.GetCustomAttribute(field, typeof (DescriptionAttribute)) as DescriptionAttribute; if (attr != null) { return attr.Description; } } } return null; } }
Now when you use MonthOfYear.January.GetDescription(), you’ll get the value in the description attribute.
To do this in reverse, getting the enum from the description, you’ll need to get all the fields for the type of enum you want to get from the description. For each of the field, if it has a Description attribute then we’ll match it on the value of the description. Otherwise, we’ll match on the name of the field.
public static TEnum? TryGetEnumFromDescription<TEnum>(this string description) where TEnum : struct, IConvertible { var type = typeof(TEnum); 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 (TEnum)field.GetValue(null); } } else { if (field.Name == description) { return (TEnum)field.GetValue(null); } } } return null; }