Get Enum Description using property in C# , .Net core
When you’re retrieving data from the database , columns of enum type often are stored as integer values . when you retrieve the data , it maps the value with the name it’s given in the enum. But sometimes we use custom description for ease of use . To display the custom description , you can follow along this article .
In this case, this is my Enum here
public enum DocumentType
{
[Display(Name = "Type 1"), Category("Test")]
Type_1= 1,
[Display(Name = "Type 2"), Category("Prod")]
Type_2 = 2,
}
public class DemoClassBase
{
public int Id { get; set; }
[Display(Name = "Document Type")]
[Required(ErrorMessage = "Document Type is required")]
public DocumentType DocType { get; set; }
}
public class CustomEnumDemoClass: DemoClassBase
{
public string DocumentTypeDisplayName
{
get
{
// Store the Enum type
var enumType = typeof(DocumentType);
// Search for public property of the specified enum type
var memberInfo = enumType.GetMember(DocType.ToString());
//Check for existance of such data
if (memberInfo.Length > 0)
{
// Retrieves a custom attribute (in this case, DisplayAttribute) applied to the enum member.
// It looks for the DisplayAttribute associated with the enum value.
var displayAttribute = (DisplayAttribute)Attribute.GetCustomAttribute(memberInfo[0], typeof(DisplayAttribute));
if (displayAttribute != null)
{
return displayAttribute.Name;
}
}
return DocumentType.ToString();
}
}
}
Here’s what’s happening
Attribute.GetCustomAttribute(...)
: This method is part of theSystem.Reflection
namespace. It is used to retrieve a custom attribute applied to a member of a type.memberInfo[0]
:memberInfo
is an array ofMemberInfo
objects representing the members (fields) of the enum. In this case, we are accessing the first (and only) member of the array, as we are interested in theDisplayAttribute
applied to the enum value.(DisplayAttribute)
: This part is a typecast. It casts the result obtained fromAttribute.GetCustomAttribute
to theDisplayAttribute
type. SinceGetCustomAttribute
returns a genericAttribute
, we cast it to the specific type we are interested in.
in Summary
“Retrieve the custom attribute (DisplayAttribute
) applied to the first member of the enum (memberInfo[0]
). If there is a DisplayAttribute
applied to this enum value, store it in the displayAttribute
variable."