I would like to know if it is possible to get attributes of the enum
values and not of the enum
itself? For example, suppose I have the following <
Here's the .NET Core version of AdamCrawford's answer, using System.Reflection.TypeExtensions;
public static class EnumHelper
{
///
/// Gets an attribute on an enum field value
///
/// The type of the attribute you want to retrieve
/// The enum value
/// The attribute of type T that exists on the enum value
/// string desc = myEnumVariable.GetAttributeOfType().Description;
public static T GetAttributeOfType(this Enum enumVal) where T : System.Attribute
{
var type = enumVal.GetType();
var memInfo = type.GetMember(enumVal.ToString());
IEnumerable attributes = memInfo[0].GetCustomAttributes(typeof(T), false);
return (T)attributes?.ToArray()[0];
}
}