Share via


Disambiguating Attribute Targets (C# Programming Guide) 

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:

public class SomeAttr : System.Attribute { }

[SomeAttr]
int Method()
{
    return 0;
}

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.

// default: applies to method
[SomeAttr]
int Method1() { return 0; } 

// applies to method
[method: SomeAttr]
int Method2() { return 0; } 

// applies to return value
[return: SomeAttr]
int Method3() { return 0; } 

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]

Parameters

  • target
    One of the following: assembly, field, event, method, module, param, property, return, type.
  • attribute-list
    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

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

Example

using System.Runtime.InteropServices;
[Guid("12345678-1234-1234-1234-123456789abc"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
interface ISampleInterface
{
    [DispId(17)]  // set the DISPID of the method
    [return: MarshalAs(UnmanagedType.Interface)]  // set the marshaling on the return type
    object DoWork();
}

See Also

Reference

Using Attributes (C# Programming Guide)
Creating Custom Attributes (C# Programming Guide)
Accessing Attributes With Reflection (C# Programming Guide)
System.Reflection
Attribute

Concepts

C# Programming Guide
Reflection (C# Programming Guide)
Attributes (C# Programming Guide)