C# Instance Constructor vs Static Constructor

Static constructor is called the first time your class is referenced i.e.

MyClass.SomeStaticMethod()

Instance constructor is called every time you do 'MyClass dummy = new MyClass()' i.e. create instance of the class

Semantically first is used when you want to ensure that some static state is initialized before it is accessed, the other is used to initialize instance members.


Static constructors allow you to initialize static variables in a class, or do other things needed to do in a class after it's first referenced in your code. They are called only once each time your program runs.

Static constructors are declared with this syntax, and can't be overloaded or have any parameters because they run when your class is referenced by its name:

static MyClass()
{
}

Instance constructors are the ones that are called whenever you create new objects (instances of classes). They're also the ones you normally use in Java and most other object-oriented languages.

You use these to give your new objects their initial state. These can be overloaded, and can take parameters:

public MyClass(int someNumber) : this(someNumber, 0) {}

public MyClass(int someNumber, int someOtherNumber)
{
    this.someNumber = someNumber;
    this.someOtherNumber = someOtherNumber;
}

Calling code:

MyClass myObject = new MyClass(100, 5);

The static constructor runs only once for all instances or uses of the class. It will run the first time you use the class. Normal constructors run when you instantiate an object of the class.

Everything you should need to know about static constructors can be found here: https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/static-constructors