Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get class DisplayName attribute value

Tags:

c#

reflection

Iv'e spent the last hour trying to get the value of a DisplayName attribute that's applied to a Class.

I find it simple enough to get the attribute values from methods and properties but I'm struggling with the class.

Could anyone help me out with this relatively small issue?

Sample below:

The Class

 [DisplayName("Opportunity")]
 public class Opportunity
 {
  // Code Omitted
 }

The Variable

var classDisplayName = typeof(T).GetCustomAttributes(typeof(DisplayNameAttribute),true).FirstOrDefault().ToString();

I have spent much time on MSDN and SO but I guess I'm missing something stupidly simple.

Either way great question for future readers too

Any help greatly appreciated!

like image 303
Tez Wingfield Avatar asked Oct 07 '15 14:10

Tez Wingfield


People also ask

What is displayName attribute?

This Active Directory attribute can be used to store a display name for the user object.

How to get Display Name in c#?

Let's try our extension method. var status = TransactionStatus. ForApproval; status. GetDisplayName();

What is the purpose of displayName class property?

The Function. displayName property in JavaScript is used to set the display name of the function. If the displayName property is used to log the name without setting the displayName property of the function than the output will be undefined.


2 Answers

using your example I got it working doing this:

 var displayName = typeof(Opportunity)
    .GetCustomAttributes(typeof(DisplayNameAttribute), true)
    .FirstOrDefault() as DisplayNameAttribute;

if (displayName != null)
    Console.WriteLine(displayName.DisplayName);

This outputted "Opportunity".

Or for the more generic way you seem to be doing it:

public static string GetDisplayName<T>()
{
    var displayName = typeof(T)
      .GetCustomAttributes(typeof(DisplayNameAttribute), true)
      .FirstOrDefault() as DisplayNameAttribute;

    if (displayName != null)
        return displayName.DisplayName;

     return "";
}

Usage:

string displayName = GetDisplayName<Opportunity>();

GetCustomAttributes() returns an object[], so you need to apply the specific cast first before accessing the required property values.

like image 112
Ric Avatar answered Oct 13 '22 08:10

Ric


Instead of ToString you need to access the DisplayName property. You can do that by casting to DisplayNameAttribute.

var classDisplayName =
    ((DisplayNameAttribute)
    typeof(Opportunity)
       .GetCustomAttributes(typeof(DisplayNameAttribute), true)
       .FirstOrDefault()).DisplayName;
like image 29
juharr Avatar answered Oct 13 '22 08:10

juharr