Export (0) Print
Expand All

Using Attributes

Attributes can be placed on most any declaration (though a specific attribute might restrict the types of declarations on which it is valid). Syntactically, an attribute is specified by placing the name of the attribute, enclosed in square brackets, in front of the declaration of the entity to which it applies. For example, a class with the attribute DllImport is declared like this:

[DllImport] public class MyDllimportClass { ... }

For more information, see DllImportAttribute Class.

Many attributes have parameters, which can be either positional (unnamed) or named. Any positional parameters must be specified in a certain order and cannot be omitted; named parameters are optional and can be specified in any order. Positional parameters are specified first. For example, these three attributes are equivalent:

[DllImport("user32.dll", SetLastError=false, ExactSpelling=false)]
[DllImport("user32.dll", ExactSpelling=false, SetLastError=false)]

The first parameter, the DLL name, is positional and always comes first; the others are named. In this case, both named parameters default to false, so they can be omitted (refer to the individual attribute's documentation for information on default parameter values).

More than one attribute can be placed on a declaration, either separately or within the same set of brackets:

bool AMethod([In][Out]ref double x);
bool AMethod([Out][In]ref double x);
bool AMethod([In,Out]ref double x);

Some attributes can be specified more than once for a given entity. An example of such a multiuse attribute is Conditional:

[Conditional("DEBUG"), Conditional("TEST1")] void TraceMethod() {...}
Note   By convention, all attribute names end with the word "Attribute" to distinguish them from other items in the .NET Framework. However, you do not need to specify the attribute suffix when using attributes in code. For example, [DllImport] is equivalent to [DllImportAttribute], but DllImportAttribute is the attribute's actual name in the .NET Framework.

See Also

Introduction to Attributes | Attribute Targets | Global Attributes | Creating Custom Attributes | Retrieving Attribute Information

© 2014 Microsoft