Search code examples
c#constructorstatic-constructor

C# Instance Constructor vs Static Constructor


What are the differences between the two? I've only used one kind of constructor and I believe it's the static constructor. Only familiar with C++ and Java.


Solution

  • 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.