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?
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; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With