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!
This Active Directory attribute can be used to store a display name for the user object.
Let's try our extension method. var status = TransactionStatus. ForApproval; status. GetDisplayName();
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.
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.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With