Obtaining Attributes


A program may query attached attributes. To obtain an attribute, two methods are available. Firstly, the method GetCustomAttributes of the class MemberInfo is available to query attributes. Note that Type inherits from MemberInfo, so this method is available to all objects of the class Type. GetCustomAttributes retrieves a list of all attributes attached to an item. One of the forms of this function is shown below.

object[] GetCustomAttributes(bool SearchBases)

When SearchBases is true, the attributes of all base classes are also included in the list. When SearchBases is false, only the attributes of the specified type will be returned.

The second way to query an attribute is through the method GetCustomAttribute, which is a static method defined by the class Attribute. The form of GetCustomAttribute is:

static Attribute GetCustomAttribute(MemberInfo mi, Type attribute)

where mi is the MemberInfo structure that describes the item for which the attribute is being queried. The attribute that is being queried is specified by the parameter attribute. For the previous example, the Comment attribute attached to the class X may be obtained as follows.

Type t = typeof(X);

type TypeAttribute = typeof(CommentAttribute);

CommentAttribute ca = (CommentAttribute)Attribute.GetCustomAttribute(t, TypeAttribute);

Once a reference to an attribute has been obtained, its members may be utilized. For example, to display the comment, the statement

Console.WriteLine(ca.Comment); 

could be used.

The next program makes use of attributes.

// Runtime10 - Attributes

using System;

[AttributeUsage(AttributeTargets.All)]
public class CommentAttribute : Attribute
{
    string c;

    public CommentAttribute(string s) { c = s; }

    public string Comment
    {
        get
        {
            return c;
        }
    }
}

[CommentAttribute("This attribute is attached to a class declaration.")]
class X { }

class Program
{
    static void Main(string[] args)
    {
        Type t = typeof(X);

        object[] attributes = t.GetCustomAttributes(false);

        Console.WriteLine("Attributes of X are:");

        foreach (object o in attributes)
            Console.WriteLine(o);

        CommentAttribute ca = (CommentAttribute)Attribute.GetCustomAttribute(t, typeof(CommentAttribute));

        Console.WriteLine("Comment is: {0}", ca.Comment);
    }
}

The output of the program is shown below.

Attributes of X are:
CommentAttribute
Comment is: This attribute is attached to a class declaration.

Notice that no object of class X was created. This demonstrates that attributes are connected to types rather than any particular object of a type.