C# Static Constructor

As you are aware now, that constructors are called when an object is created, so static constructors are used to initialize any static data. It is called automatically before first instance of class is created.

It can only access the static member(s) of the class. Static constructor cannot be parameterized constructors, means they cannot have paramters inside it.

Also, each Class can have only one static constructor only, while we can have multiple paramterized constructors.

Syntax

public Class Class_Name{

   static Class_Name(){
     //do something with static members.
   }

}

One more things to note about static constructor is that, static constructors cannot have access modifiers.

Let's take a look at an example of static constructor.

using System;
					
public class A
{
  static A()
  {
    Console.WriteLine("Static A Constructor");
  }
  public static void display()
  {
    Console.WriteLine("Display the Static Method of A Class");
  }
}
public class B
{
  static B()
  {
    Console.WriteLine("Static B Constructor");
  }
  public static void display()
  {
    Console.WriteLine("Display the Static Method of B Class");
  }
}

public class StaticConstructorExample
{
  public static void Main()
  {
    A.display();
    Console.WriteLine();
    B.display();
  }
}

Output:

Static A Constructor
Display the Static Method of A Class

Static B Constructor
Display the Static Method of B Class

As you can see in the above example, we have created static constructor and static method "Display()" for both classes A and B, when calling methods of each class, we are not creating any object as methods are also static, also notice Static Constructor is called before method is called and code inside it is executed.

We didn't needed to create object to access static constructor because a static constructor is called automatically to initialize the class before the first instance is created or any static members are referenced.

A static constructor cannot be called directly and the user has no control on when the static constructor is executed in the program.


Share Tweet