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).
C++ doesn't have static constructors, as Java or C# does, so you usually have to initialize the static data members one by one (independently). This is a limitation because you may want to initialize several static data members in the same loop or algorithm, for example.
Static Constructors should not have any parameters. static constructor does not contain parameters. static constructor is called when the execution of the class is started. It is the first member to be execute in the class.
8. Why do we use static constructors? Explanation: Static constructors help in initializing the static members of the class. This is provided because the static members are not considered to be property of the object, rather they are considered as the property of class.
1. Static constructor is called before the first instance of class is created, wheras private constructor is called after the first instance of class is created. 2. Static constructor will be executed only once, whereas private constructor is executed everytime, whenever it is called.
From MSDN:
When a constructor declaration includes an extern modifier, the constructor is said to be an external constructor. Because an external constructor declaration provides no actual implementation, its constructor-body consists of a semicolon.
...
It seems we can't think of a good reason of using this declaration and it sure correct. But when you dig further you realize there's a whole world of dynamic assembling or - Code Generation.
If you were to develop a compiler for the .NET platform you'll probably need some trickery solutions as does the C# compiler use. I can realize that some core implementations uses extern constructor which is implemented somewhere else for good design reasons.
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