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]
where:
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;
[Guid("12345678-1234-1234-1234-123456789abc"),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
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();
}
Introduction to Attributes |