Enum Overview
In our sample enum file, we created TransactionStatus
where it has enum values and ids. We also used the using System.ComponentModel.DataAnnotations
so we can use the attribute [Display(Name = "")]
So let’s create our extension method.
using System;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Reflection;
namespace ConsoleApp
{
public static class EnumExtensions
{
public static string GetDisplayName(this Enum enumValue)
{
return enumValue.GetType()
.GetMember(enumValue.ToString())
.First()
.GetCustomAttribute<DisplayAttribute>()
?.GetName();
}
}
}
Sample Usage
Let’s try our extension method.
var status = TransactionStatus.ForApproval;
status.GetDisplayName();
Then it will display For Approval.
If you have some questions or comments, please drop it below 👇 :)
