I have a class, lets call it Book with a property called Name. With that property, I have an attribute associated with it.
public class Book
{
[Author("AuthorName")]
public string Name
{
get; private set;
}
}
In my main method, I'm using reflection and wish to get key value pair of each attribute for each property. So in this example, I'd expect to see "Author" for attribute name and "AuthorName" for the attribute value.
Question: How do I get the attribute name and value on my properties using Reflection?
If you just want one specific Attribute value For instance Display Attribute you can use the following code:
You can use
GetCustomAttributesData()
andGetCustomAttributes()
:Here are some static methods you can use to get the MaxLength, or any other attribute.
Using the static method...
Or using the optional extension method on an instance...
Or using the full static method for any other attribute (StringLength for example)...
Inspired by the Mikael Engver's answer.
to get attribute from enum, i'm using :
// Using
I have solved similar problems by writing a Generic Extension Property Attribute Helper:
Usage: