I've been working with Reflections and wanted to get all the attributes declared for a property. There are two properties under PropertInfo
class which are CustomAttributes
and Attributes
.
According to the MSDN, they are explained as follows:
Attributes:
This property represents the attributes associated with a member. All members have a set of attributes that are defined in relation to the specific type of member. The property attributes let the user know if this property is the default property, a SpecialName property, and so on.
Note: The code sample given in the PropertyInfo.Attributes
page doesn't even work.
Custom Attributes:
An array that contains all the custom attributes applied to this member, or an array with zero elements if no attributes are defined.
However, when I run this code for them, Attributes
returns nothing while CustomAttributes
returns Required
.
void Main() { var attributes = typeof(Myproperty).GetProperty("Caption").CustomAttributes; //var attributes = typeof(Myproperty).GetProperty("Caption").Attributes; attributes.Dump(); //Dump is a LinqPad method which dumps everything to the outpu window } public class Myproperty { private string caption = "Default caption"; [Required] public string Caption { get{return caption;} set {if(caption!=value) {caption = value;} } } }
AttributeUsage attribute defines the program entities to which the attribute can be applied. We can use reflection to discover information about a program entity at runtime and to create an instance of a type at runtime. Most of the classes and interfaces needed for reflection are defined in the System.
Attributes provide a powerful method of associating metadata, or declarative information, with code (assemblies, types, methods, properties, and so forth). After an attribute is associated with a program entity, the attribute can be queried at run time by using a technique called reflection.
Advertisements. An attribute is a declarative tag that is used to convey information to runtime about the behaviors of various elements like classes, methods, structures, enumerators, assemblies etc. in your program. You can add declarative information to a program by using an attribute.
PropertyInfo.Attributes doesn't have anything to do with the Attribute class. Check the PropertyAttributes enumeration for values you may encounter. These are CLR implementation details that have no obvious connection to C# code. Yes, that was an unfortunate naming choice.
To find attributes like your [Required] attribute you must use the CustomAttributes property.
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