Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the purpose of the method attribute-target?

Tags:

c#

attributes

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?

like image 383
vcsjones Avatar asked Mar 27 '13 14:03

vcsjones


1 Answers

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; } 
like image 200
Botz3000 Avatar answered Oct 05 '22 22:10

Botz3000