Export (0) Print
Expand All

Attribute Targets

In certain situations, the target of an attribute (that is, the entity to which the attribute applies) appears to be ambiguous. For example, in the following method declaration, the SomeAttr attribute could apply to the method or to the method's return value:

[SomeAttr] int Method1( string s )

This sort of situation arises frequently when marshaling. To resolve the ambiguity, C# has a set of default targets for each kind of declaration, which can be overridden by explicitly specifying attribute targets.

[method: SomeAttr] int Method1( string s ) // applies to method
[return: SomeAttr] int Method1( string s ) // applies to return value
[SomeAttr] int Method1( string s ) // default: applies to method

Note that this is independent of the targets on which SomeAttr is defined to be valid (see AttributeUsage); that is, even if SomeAttr were defined to apply only to return values, the return target would still have to be specified. In other words, the compiler will not use AttributeUsage information to resolve ambiguous attribute targets.

The syntax for attribute targets is as follows:

[target : attribute-list]


One of the following: assembly, field, event, method, module, param, property, return, type.
A list of applicable attributes.

The table below lists all declarations where attributes are allowed; for each declaration, the possible targets for attributes on the declaration are listed in the second column. Targets in bold are the defaults.

Declaration Possible targets
assembly assembly
module module
class type
struct type
interface type
enum type
delegate type, return
method method, return
parameter param
field field
property — indexer property
property — get accessor method, return
property — set accessor method, param, return
event — field event, field, method
event — property event, property
event — add method, param
event — remove method, param

Note that assembly- and module-level attributes have no default target. For more information, see Global Attributes.


// cs_attribute_targets.cs
// compile with: /target:library
using System.Runtime.InteropServices;

interface IMyInterface
   [DispId(17)]                  // set the DISPID of the method
   // the following attribute sets the marshaling on the return type
   [return : MarshalAs(UnmanagedType.Interface)]
   object MyInterfaceMethod();

See Also

Introduction to Attributes | 17.2 Attribute specification | Global Attributes | Creating Custom Attributes | Retrieving Attribute Information

© 2014 Microsoft