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!
Instead of
ToString
you need to access theDisplayName
property. You can do that by casting toDisplayNameAttribute
.Try this:
using your example I got it working doing this:
This outputted "Opportunity".
Or for the more generic way you seem to be doing it:
Usage:
GetCustomAttributes()
returns anobject[]
, so you need to apply the specific cast first before accessing the required property values.Some valid solutions already exist but you could also create an extension method like this:
The way you use this is by providing the name of the property as a string and then the type of the class.
I think this is more dynamic and cleaner than some other solutions around. It might be a good idea to wrap it all with a try/catch statement because of it's dynamic nature.