Share via


Using Attributes (C# Programming Guide)

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 method with the attribute DllImport is declared like this:

[System.Runtime.InteropServices.DllImport("user32.dll")]
extern static void SampleMethod();

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")]
[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:

void MethodA([In][Out] ref double x) { }
void MethodB([Out][In] ref double x) { }
void MethodC([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

Concepts

C# Programming Guide

Reference

Reflection (C# Programming Guide)

Attributes (C# Programming Guide)

Disambiguating Attribute Targets (C# Programming Guide)

Creating Custom Attributes (C# Programming Guide)

Accessing Attributes With Reflection (C# Programming Guide)

Attribute

System.Reflection