I've created a custom generic method to get any attribute value from an enum.
public static class EnumHelper
{
public static string GetAttributeValueByEnumValue<EnumType, AttributeType>(EnumType value, string attributeProperty = null)
where EnumType : Enum
where AttributeType : Attribute
{
var enumField = value.GetType().GetField(value.ToString());
var enumAttributes = enumField?.GetCustomAttributes(typeof(AttributeType), false) as AttributeType[];
if (enumAttributes == null || !enumAttributes.Any())
throw new Exception($"Attribute [{typeof(AttributeType).Name}] not found in enum [{typeof(EnumType).Name}] type with value [{value.ToString()}]!");
var enumAttribute = enumAttributes.First();
var attributeValue = enumAttribute
.GetType()
?.GetProperty(!string.IsNullOrEmpty(attributeProperty) ? attributeProperty : typeof(AttributeType).Name.Replace("Attribute", string.Empty))
?.GetValue(enumAttribute);
if (attributeValue == null)
throw new Exception("Error reading enum attribute value!");
return attributeValue.ToString();
}
}
To use it, simply call it like below:
EnumHelper.GetAttributeValueByEnumValue<EnumLookup, DescriptionAttribute>(enumValue);
You can also provide the attributeProperty name in case of a custom enum, like below:
EnumHelper.GetAttributeValueByEnumValue<EnumLookup, TitleAttribute>(enumValue, "TitleName");
I hope it helps you :)