8.8. Runtime Discovery of Attributes Using Reflection

Now that we've decorated our classes with custom attributes, we'll want to access them during the execution of our program. There are several ways to do that. For example, we can invoke the static GetCustomAttributes() method of the Attribute class, passing it a Type object:

static public void retrieveClass1( object obj )
{
    Type tp = obj.GetType();

    Attribute [] attrs =
                 Attribute.GetCustomAttributes( tp );

An Attribute array holding an instance of each custom attribute retrieved is returned. If no custom attributes are present, an empty array is returned. Note that intrinsic attributes are not retrieved. For example, the intrinsic Serializable attribute of our class is not returned.

The instance ...

Get C# Primer: A Practical Approach now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.