-
Book Overview & Buying
-
Table Of Contents
Metaprogramming in C#
By :
Since attributes are created at compile time and do not require you to have an instance of a type that has been associated with attributes, you can discover attributes using the type system.
If you look at the System.Type type, you’ll see that it implements a type called MemberInfo that sits in the System.Reflection namespace. This base class serves as the base class for PropertyInfo, MethodInfo, FieldInfo, and most of the specific info types representing code elements we can discover through the type system.
On the MemberInfo type, you find a method called GetCustomAttributes(). This lets you get a collection of attributes associated with the particular code element.
Take the class we had before:
[Custom]
public class MyClass
{
}
You can then quite easily get to the custom attributes on a type and loop through them and perform the actions you want to:
foreach( var attr in typeof(MyClass).GetCustomAttributes() )
{
...