Wednesday, March 24, 2010

Attributes

Attributes are additional declarative information that can modify the declaration of program entities (types, members, parameters, and so forth). At run time the compiler can retrieve this information through a process called reflection. Attributes can be either predefined or user – defined. In most cases, programmers use the predefined attributes. Attributes server different purpose, such as marking a method as deprecated, indicating conditional compilation, setting a type layout, and so forth.
Attributes are derived from the abstract class System.Attribute, which defines the services of attributes. By convention, all attributes have the suffix Attribute, sucha as DIIImportAttribute. We can skip the suffix and just use the attribute alias, which is DllImport.
The attribute is written between brackets like this example:
[method:DllImport(“user32.dll”)]
Notice that brackets are part of the attribute syntax. Do not confuse these brackets with those that indicate the optional part of the syntax.
The word “method” in this in this attribute represents the target to which the attribute is applied. In this example, the attribute applied is to a method in the library user32.dll. In most cases, the target is opetional; it is necessary only if there is ambiguity. For instance, add the target if the attribute can be applied to a method or a return type.
In this example, the attribute is written without the target element:
[DllImport(“user32.dll”)]
Target elements can be any of the following:
•    assembly
•    field
•    event
•    method
•    parameter
•    property
•    return
•    type
When using an attribute, either qualify its name or use the appropriate using directive. The following are some commonly used attributes that exist in various namespaces:
•    System.Obsolete.Attribute
•    System.Diagnostics.ConditionalAttribute
•    System.Runtime.InteropServices.DllImportAttribute
•    System.Xml.Serialization.XmlArrayAttribute

No comments:

Post a Comment