A static constructor is a way to initialize any static data or to perform a particular action that needs to be performed only once.
A static constructor is called automatically before the first instance is created or any static member is referenced.
Syntax:
public static class SomeClass { static int i; static SomeClass() { i =10; } }
You can use static constructors to initialize static fields only.
It runs at an indeterminate time before any of those fields are used or referenced.
Following are some key characteristics and keep-in-mind points regarding static constructors:
- Static constructors cannot have access modifiers or have parameters.
- A static constructor is called automatically to initialize the class before the first instance is created or any static member is referenced.
- A static constructor cannot be called directly. The user has no control over calling the static constructor explicitly.
- Static constructors cannot be inherited, each class has to have its own static constructor.
- Static constructors cannot be overloaded, which means you cannot have more than one static constructor in the same class.
- If a static constructor throws an exception, you will get a TypeInitializerException.
Static constructors initialize the class, which is to say that they are called automatically before any other static members are accessed, or before the creation of any instances of the class.
As for the ordering of calls to static constructors in an inherited class hierarchy, it goes from Child to Parent class (in the upward direction).