12

While browsing the C# Language Specification 5.0 I became aware that you can define an extern event. I'm used to extern methods for platform invoke, and native callbacks. I have not run across this concept in my eleven years in the .NET world.

  • What does an extern event interoperate with?
  • Does it provide the ability to subscribe to some native event?
  • Can you raise such an event?
  • What problems does it solve that earned its place in the C# language?

I searched the specs for 'extern' and discovered that properties, indexers, constructors, static constructors, finalizers (!) and even operators (!) can all be extern. Fields can't. (I also learned that a namespace alias can be 'extern', but it means something quite different.)

Edit: That clarifies things. So extern applies not to the event concept or property concept but to the constituent methods. Is that correct? Are COM events any different than DllImport events?

jnm2
  • 7,960
  • 5
  • 61
  • 99
  • That is not "pseudo" syntax, it is the code that's generated by the type library importer tool, Tlbimp.exe. Writing [ComImport] declarations by hand is sometimes done, only when there is no type library available for the component. The *extern* modifier can be used on any declaration that's implemented as a method under the hood, the add and remove accessors in case of an event. The C# compiler just blindly assumes that the jitter will be able to provide the implementation. – Hans Passant Aug 14 '14 at 15:34

1 Answers1

4

I have never seen this before, and a search does not really bring up any real-world uses, but can find it in the Roslyn compiler testsuite:

using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;

public class C
{
    [method: DllImport("c")]
    public extern static event System.Action G;
}

The test verifies that this imports the add_G and remove_G functions from the c DLL. Since only the accessor methods are imported, there is no way for C or any of its users to raise the event, that can only be done by the external DLL.

I suspect it's just there for completeness. The extern keyword was already there, and it would quite possibly be more work to reject it in combination with events than to make it work.

As for your edit, properties, indexers, constructors, static constructors, finalizers, operators all have one thing in common: they're methods. Fancy methods, but methods nonetheless. The same for event accessors. And since methods can be extern, that applies to all methods unless the rules have specific exceptions. Specific exceptions require work, and the benefits of that work have to outweigh the costs. In this case, there are pretty much no benefits to rejecting extern in such cases.