X hits on this document





314 / 396

Chapter ‎18   Unsafe code

17. Attributes

Much of the C# language enables the programmer to specify declarative information about the entities defined in the program. For example, the accessibility of a method in a class is specified by decorating it with the method-modifiers public, protected, internal, and private.

C# enables programmers to invent new kinds of declarative information, called attributes. Programmers can then attach attributes to various program entities, and retrieve attribute information in a run-time environment. For instance, a framework might define a HelpAttribute attribute that can be placed on certain program elements (such as classes and methods) to provide a mapping from those program elements to their documentation.

Attributes are defined through the declaration of attribute classes (§‎17.1), which may have positional and named parameters (§‎17.1.2). Attributes are attached to entities in a C# program using attribute specifications (§‎17.2), and can be retrieved at run-time as attribute instances (§‎17.3).

17.1 Attribute classes

A class that derives from the abstract class System.Attribute, whether directly or indirectly, is an attribute class. The declaration of an attribute class defines a new kind of attribute that can be placed on a declaration. By convention, attribute classes are named with a suffix of Attribute. Uses of an attribute may either include or omit this suffix.

17.1.1 Attribute usage

The attribute AttributeUsage (§‎17.4.1) is used to describe how an attribute class can be used.

AttributeUsage has a positional parameter (§‎17.1.2) that enables an attribute class to specify the kinds of declarations on which it can be used. The example

using System;

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface)] public class SimpleAttribute: Attribute { ... }

defines an attribute class named SimpleAttribute that can be placed on class-declarations and interface-declarations only. The example

[Simple] class Class1 {...}

[Simple] interface Interface1 {...}

shows several uses of the Simple attribute. Although this attribute is defined with the name SimpleAttribute, when this attribute is used, the Attribute suffix may be omitted, resulting in the short name Simple. Thus, the example above is semantically equivalent to the following:

[SimpleAttribute] class Class1 {...}

[SimpleAttribute] interface Interface1 {...}

AttributeUsage has a named parameter (§‎17.1.2) called AllowMultiple, which indicates whether the attribute can be specified more than once for a given entity. If AllowMultiple for an attribute class is true, then that attribute class is a multi-use attribute class, and can be specified more than once on an entity. If AllowMultiple for an

Copyright Microsoft Corporation 1999-2003. All Rights Reserved.301

Document info
Document views1273
Page views1273
Page last viewedFri Jan 20 14:16:39 UTC 2017