Please explain to me the use of static constructor. Why and when would we create a static constructor and is it possible to overload one?
C# – the use of static constructors
cconstructorstatic-constructor
Related Topic
- C# – the difference between const and readonly in C#
- C++ – What does the explicit keyword mean
- C# – What are the correct version numbers for C#
- Java – How to call one constructor from another in Java
- C# – Case insensitive ‘Contains(string)’
- C# – Proper use of the IDisposable interface
- C# – Call one constructor from another
Best Answer
No you can't overload it; a static constructor is useful for initializing any static fields associated with a type (or any other per-type operations) - useful in particular for reading required configuration data into readonly fields, etc.
It is run automatically by the runtime the first time it is needed (the exact rules there are complicated (see "beforefieldinit"), and changed subtly between CLR2 and CLR4). Unless you abuse reflection, it is guaranteed to run at most once (even if two threads arrive at the same time).