An attribute is a declarative tag used to communicate runtime information about the actions of different elements in your software, such as classes, methods, structures, enumerators, assemblies, etc. By using an attribute, you can add declarative information to a programme. A declarative tag is represented by brackets placed above the element for which it is used, square]).
Attributes are used to add metadata to a programme, such as instructions for the compiler, and other information, such as notes, explanations, methods, and classes. Two types of attributes are supported by the .Net Framework: pre-defined attributes and custom created attributes.
Specifying an Attribute
Syntax for specifying an attribute is as follows −
|[attribute(positional_parameters, name_parameter = value, ...)]element
Inside square brackets, the attribute name and its values are defined before the element to which the attribute is applied. Place parameters define the critical information and optional information is specified by the name parameters.
The .Net Framework provides three pre-defined attributes −
The pre-defined AttributeUsage attribute defines how it is possible to use a custom attribute class. This determines the types of objects on which you can add the attribute.
The syntax for this attribute is as follows—
AllowMultiple = allowmultiple,
Inherited = inherited
1. The validon parameter defines the language elements the attribute can be put on. This is a variation of the value of the AttributeTarget enumerator. The default value for this setting is AttributeTargets. All.
2. The allowmultiple (optional) parameter provides a Boolean value for the AllowMultiple property of this attribute. The attribute is multipurpose, if this is valid. False (single-use) is the norm.
3. The inherited (optional) parameter provides a Boolean value for the inherited property of this attribute. If it is valid, derived classes inherit the attribute. The meaning is false (not inherited) by nature.
AllowMultiple = true) ]
This predefined attribute marks a conditional method whose execution depends on a preprocessing identifier that has been stated.
Depending on the defined value, such as Debug or Trace, this causes the conditional compilation of method calls. For instance, while debugging a code, it shows the values of the variables.
Syntax for specifying this attribute is as follows −
A programme object that should not be used is identified by this predefined attribute. It allows you to notify the compiler that a specific target element should be discarded. For instance, if you are using a new method in a class and you still want to keep the old method in the class, you can label it as obsolete by showing a new method message instead of the old method.