Static Constructor in c#

Static Constructor :  


static Constructor need not to create an instance of the class.

Static constructors are used to initializing the static members of the class and implicitly

 called before the creation of the first instance of the class. 



  • A static constructor does not take access modifiers or have parameters.

  • A class or struct can only have one static constructor.

  • Static constructors cannot be inherited or overloaded.

  • A static constructor cannot be called directly and is only meant to be called by the common language runtime (CLR). It is invoked automatically.

  • The user has no control on when the static constructor is executed in the program.

  • A static constructor is called automatically to initialize the class before the first instance is created or any static members are referenced. 


  class Program
  {
    static int I;
    static Program()
    {
      I = 100;
      Console.WriteLine("Static Constructor called");
    }
    public Program()
    {
      Console.WriteLine("Instance Constructor called");
    }
    public static void Main()
    {
      Program P = new Program();
    }
  }



Can you mark static constructor with access modifiers?

No, we can't use access modifiers on static constructor.


Can you have parameters for static constructors?

No, static constructor can't have parameters.


What happens if a static constructor throws an exception?

if a static constructor throws an exception, the runtime will not invoke it a second time, and the type will remain uninitialized for the lifetime of the application domain in which your program is running.


Can a class or a struct have multiple static constructors?


No.



Can a child class call the constructor of a base class?


Yes, a child class can call the constructor of a base class by using the base keyword as shown in the example below.

using System;
namespace TestConsole
{
  class BaseClass
  {
    public BaseClass(string str)
    {
      Console.WriteLine(str);
    }
  }

  class ChildClass : BaseClass
  {
    public ChildClass(string str): base(str)
    {
    }

    public static void Main()
    {
      ChildClass CC = new ChildClass("Calling base class constructor from child class");
    }
  }
}

If a child class instance is created, which class constructor is called first - base class or child class?


When an instance of a child class is created, the base class constructor is called before the child class constructor. An example is shown below.

using System;
namespace TestConsole
{
  class BaseClass
  {
    public BaseClass()
    {
      Console.WriteLine("I am a base class constructor");
    }
  }
  class ChildClass : BaseClass
  {
    public ChildClass()
    {
      Console.WriteLine("I am a child class constructor");
    }
    public static void Main()
    {
      ChildClass CC = new ChildClass();
    }
  }
}