An attribute is a piece of additional declarative information that is specified for a declaration. Attributes can be specified for type-declarations, class-member-declarations, interface-member-declarations, enum-member-declarations, property-accessor-declarations and formal-parameter declarations.
Attributes are specified in attribute sections. Each attribute section is surrounded in square brackets, with multiple attributes specified in a comma-separated lists. The order in which attributes are specified, and the manner in which they are arranged in sections is not significant. The attribute specifications [A][B]
, [B][A]
, [A, B]
, and [B, A]
are equivalent.
An attribute consists of an attribute-name and an optional list of positional and named arguments. The positional arguments (if any) precede the named arguments. A positional argument consists of an attribute-argument-expression; a named argument consists of a name, followed by an equal sign, followed by an attribute-argument-expression.
The attribute-name identifies either a reserved attribute or an attribute class. If the form of attribute-name is type-name then this name must refer to an attribute class. Otherwise, a compile-time error occurs. The example
class Class1 {} [Class1] class Class2 {} // Error
is in error because it attempts to use Class1
, which is not an attribute class, as an attribute class.
It is an error to use a single-use attribute class more than once on the same entity. The example
[AttributeUsage(AttributeTargets.Class)] public class HelpStringAttribute: System.Attribute { string value; public HelpStringAttribute(string value) { this.value = value; } public string Value { get {…} } } [HelpString("Description of Class1")] [HelpString("Another description of Class1")] public class Class1 {}
is in error because it attempts to use HelpString
, which is a single-use attribute class, more than once on the declaration of Class1
.
An expression E
is an attribute-argument-expression if all of the following statements are true:
E
is an attribute parameter type (§17.1.3).E
can be resolved to one of the following:
System.Type
object.