Accordingly to the section "10.12 Static constructors" of "C# Language Specification. Version 5.0" static constructor can be marked with "extern" modifier and in this case it's said to be an external static constructor.
The ordinary (non-external) static constructors are well known. They are used to initialize static fields and properties.
The external static methods are often used to call native functions via P/Invoke.
And I'm also aware of quite esoteric extern constructors (see also this question). For instance, String
class has several such declarations, these constructors are implemented by the runtime.
But are the any real usages of external static constructors? I've searched through the coreclr repo and found nothing. The language specification couldn't give a description to some construct that has never ever been used in the wild. Or could?
My guess: C# has external static constructors just because CLR supports them (in principle).
extern
does is set the RVA of the method to 0. The runtime is left to figure out the rest. See also https://mcmap.net/q/873252/-when-is-it-appropriate-to-use-the-extern-keyword-without-using-the-dllimport-attribute . There's little reason for the language spec to forbid this since the work of the compiler is trivial (it would be more work to outlaw it). Furthermore, since constructors can't be markedDllImport
, the only way to implement such methods is withMethodImplOptions.InternalCall
, so the runtime is the only possible consumer, making it even less interesting to explicitly forbid it. – Spagyric