Disambiguating Attribute Targets (C# Programming Guide)
Updated: January 2010
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:
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.
Note that this is independent of the targets on which SomeAttr is defined to be valid; 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. For more information, see AttributeUsage (C# Programming Guide).
The syntax for attribute targets is as follows:
[target : attribute-list]
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.
property/indexer — get accessor
Property/indexer — set accessor
method, param, return
event (field or field-like)
event, field, method
event — add accessor
event — remove accessor
Assembly and module-level attributes have no default target. For more information, see Global Attributes.