What is the purpose of the target method?

The C # specification (17.2) states that when specifying an attribute, there are several target attributes. This is often the case when you need to apply an attribute to something that often has a β€œreal” place to specify the attribute. For example, the return target is often used in the Invoke platform:

 [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, such as method :

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

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

+7
source share
1 answer

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

In addition, I think that in such cases, an additional qualifier makes things clearer:

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

All Articles