Attributes


Declarative information may be added to a program in the form of attributes. Attributes are metadata. An attribute is specified between square brackets and it precedes the item to which it applies. An attribute is not a member of a class; rather, an attribute supplies additional information that is attached to an item.

An attribute class must derive from the class System.Attribute. The class Attribute defines substantial functionality, but this functionality is not always required by deriving classes. Attribute class often use the suffix Attribute as part of their name; although, this is not a requirement.

When declaring an attribute, it is preceded by a built-in attribute called AttributeUsage. The built-in attribute specifies the types of items to which the newly declared attribute may be applied. For example, the use of an attribute may be restricted to methods.

The data supported by an attribute is declared within the attribute class. Usually, attribute classes are quite small. An example of an attribute class is shown below.

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

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

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

The name of the attribute is CommentAttribute. Its declaration is preceded by an AttributeUsage attribute. The AttributeUsage specifies that the attribute may be applied to all item types. CommentAttribute derives from Attribute (as it must). The class CommentAttribute contains a single string field call c (which is private). This is the actual comment string. A public property called Comment is used to access the value of the field c. A single constructor that accepts a string is available. The constructor copies the specified string to the field c. This completes the definition of CommentAttribute, which is ready for use.

To apply an attribute to an item, a call to a constructor of the attribute is enclosed in brackets and precedes the item to which it is applied. For example, to apply CommentAttribute to a class the following code may be used.

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

This code constructs a CommentAttribute and attaches it to class X. The attribute contains the string "This attribute is attached to a class declaration.". When attaching the attribute, the full name is not required when it has the suffix Attribute. For example, the previous declaration could be done the following way.

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