Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to display the name of enum display attribute [duplicate]

Tags:

c#

enums

This is my enum.

public enum ContractType
{
    [Display(Name = "Permanent")]
    Permanent= 1,

    [Display(Name = "Part Time")]
    PartTime= 2,

}

I try to get display name using below code.

 string x = Enum.GetName(typeof(ContractType), 2);

But it is return "PartTime" always. Actually I want to get the name of display attribute. For above example x should be assigned Part Time

I saw there are solutions which having huge code. Doesn't this have a simple/one line solution?

Please show me a direction.

like image 957
weeraa Avatar asked Dec 06 '16 12:12

weeraa


People also ask

How do I find the name of an enum?

Enum. GetName(Type, Object) Method is used to get the name of the constant in the specified enumeration that has the specified value. Syntax: public static string GetName (Type enumType, object value);

How do you display the value of an enum?

An enumeration is a great way to define a set of constant values in a single data type. If you want to display an enum's element name on your UI directly by calling its ToString() method, it will be displayed as it has been defined.


1 Answers

Given an enum

public enum ContractType
{
   [Display(Name = "Permanent")]
   Permanent= 1,

   [Display(Name = "Part Time")]
   PartTime //Automatically 2 you dont need to specify
}

Custom method to get the data annotation display name.

//This is a extension class of enum
public static string GetEnumDisplayName(this Enum enumType)
{
    return enumType.GetType().GetMember(enumType.ToString())
                   .First()
                   .GetCustomAttribute<DisplayAttribute>()
                   .Name;
}

Calling GetDisplayName()

ContractType.Permanent.GetEnumDisplayName();

Hope this helps :)

like image 63
dijam Avatar answered Sep 21 '22 15:09

dijam