vcsjones
vcsjones

Reputation: 141703

What is the purpose of the method attribute-target?

In the C# specification (17.2) it indicates there are several attribute targets when specifying an attribute. This is common when you need to apply an attribute to something that doesn't often have a "real" place to specify an attribute. For example, the return target is used often in platform Invoke:

[return: MarshalAs(UnmanagedType.Bool)]
static extern bool SomeWin32Method(); //Assume this is valid, has a DllImport, etc.

However I noticed that there are other attribute targets, like method:

[method: DllImport("somelib.dll")]
static extern bool SomeWin32Method();

Under what circumstances would I need to explicitly define the method attribute target (say to resolve ambiguity), or is it just there for the sake of completeness?

Upvotes: 8

Views: 579

Answers (1)

Botz3000
Botz3000

Reputation: 39670

You don't need to specify the target in this case (located directly above a method, method is the default target), it's just there for completeness. Just like you don't need to specify private when adding members to a class, but many people do it anyway. And in many cases code generators like to be extra explicit about things.

Also, i think in cases like this, the additional specifier makes things a bit more clear:

[method: SomeAttr]
[return: SomeOtherAttr]
int SomeMethod() { return 0; } 

Upvotes: 8

Related Questions