What is a static constructor?

In C#, a static constructor (also called a type initializer) is a special constructor that is used to initialize static members of a class. It is defined using the static keyword and does not take any parameters. A static constructor is called automatically before any static members of the class are accessed or any instance of the class is created.

Here are some key points about static constructors:

  1. Syntax:
    • A static constructor is declared using the static keyword followed by the class name and parentheses, like static ClassName().
    • It does not have an access modifier, and it cannot be overloaded or called explicitly.
  2. Execution:
    • The static constructor is automatically executed once, and only once, when the class is accessed or an instance of the class is created.
    • It is executed before any static members are accessed or any static methods are called.
    • The runtime ensures that the static constructor is executed before the class is used.
  3. Purpose:
    • The primary purpose of a static constructor is to initialize static fields or perform any one-time initialization logic for the class.
    • It is often used to initialize static data, set up static resources, or perform other initialization tasks that need to be done before using the class.
  4. Restrictions:
    • A static constructor cannot be called directly or used to create an instance of the class.
    • It cannot have any parameters.
    • It cannot have an explicit this or base constructor call.

Here’s an example that demonstrates the usage of a static constructor:

public class MyClass
    static int count;
    static readonly DateTime creationTime;

    static MyClass()
        count = 0;
        creationTime = DateTime.Now;

    public static void IncrementCount()

    public static void DisplayCount()
        Console.WriteLine("Count: " + count);

    public static void DisplayCreationTime()
        Console.WriteLine("Creation Time: " + creationTime);

In this example, the static constructor initializes the count variable to 0 and assigns the current date and time to the creationTime variable. The static methods IncrementCount(), DisplayCount(), and DisplayCreationTime() can be called to manipulate and display the values of the static members.

Static constructors are useful when you need to initialize static members or perform one-time initialization for a class. They allow you to ensure that certain initialization tasks are performed before the class is used and provide a convenient way to set up static resources or data.

error: Content is protected !!