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:



Table Of Contents