Get Enum Description using property in C# , .Net core

Arian Rahman
2 min readMar 7, 2024

--

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

  1. Attribute.GetCustomAttribute(...): This method is part of the System.Reflection namespace. It is used to retrieve a custom attribute applied to a member of a type.
  2. memberInfo[0]: memberInfo is an array of MemberInfo 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 the DisplayAttribute applied to the enum value.
  3. (DisplayAttribute): This part is a typecast. It casts the result obtained from Attribute.GetCustomAttribute to the DisplayAttribute type. Since GetCustomAttribute returns a generic Attribute, 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."

--

--

Arian Rahman

A Software developer and an aspiring Data Scientist ... That's it ! LinkedIn : https://www.linkedin.com/in/arianrahman/