Reading an attribute

suggest change

Method GetCustomAttributes returns an array of custom attributes applied to the member. After retrieving this array you can search for one or more specific attributes.

var attribute = typeof(MyClass).GetCustomAttributes().OfType<MyCustomAttribute>().Single();

Or iterate through them

foreach(var attribute in typeof(MyClass).GetCustomAttributes()) {
    Console.WriteLine(attribute.GetType());
}

GetCustomAttribute extension method from System.Reflection.CustomAttributeExtensions retrieves a custom attribute of a specified type, it can be applied to any MemberInfo.

var attribute = (MyCustomAttribute) typeof(MyClass).GetCustomAttribute(typeof(MyCustomAttribute));

GetCustomAttribute also has generic signature to specify type of attribute to search for.

var attribute = typeof(MyClass).GetCustomAttribute<MyCustomAttribute>();

Boolean argument inherit can be passed to both of those methods. If this value set to true the ancestors of element would be also to inspected.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Attributes:
* Reading an attribute

Table Of Contents
17 Regex
19 Arrays
21 Enum
22 Tuples
24 GUID
27 Looping
36 Casting
46 Methods
88 Events
92 Structs
93 Attributes
104 Indexer
106 Stream
107 Timers
109 Threading
127 Caching
135 Pointers
147 C# Script