Let's have two code snippets:
A:
public class Foo
{
private static Bar _unused = new Bar();
}
B:
public class Foo
{
private static Bar _unused;
static Foo()
{
_unused = new Bar();
}
}
In case A the CLR will not even call the Bar ctor (unless it is debug build or the debugger is attached), however in case B it is called under all circumstances.
The thing is that in Bar constructor one can have calls that will make this instance reachable from elsewhere - most typically events subscriptions.
So:
If you don't create a constructor:
The static field variable initializers of a class correspond to a sequence of assignments that are executed in the textual order in which they appear in the class declaration. If a static constructor (Section 10.11) exists in the class, execution of the static field initializers occurs immediately prior to executing that static constructor. Otherwise, the static field initializers are executed at an implementation-dependent time prior to the first use of a static field of that class.
If you do have a static constructor:
A static constructor is used to initialize any static data, or to perform a particular action that needs to be performed once only. It is called automatically before the first instance is created or any static members are referenced.
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