0
0
CsharpConceptBeginner · 3 min read

What is Static Constructor in C# and How It Works

A static constructor in C# is a special method that initializes static members of a class. It runs automatically once before any instance is created or any static member is accessed, without needing to be called explicitly.
⚙️

How It Works

A static constructor is like a setup routine that runs only once for a class. Imagine you have a machine that needs some initial adjustments before it can start working. The static constructor does this setup for the class's static parts before anything else happens.

It runs automatically the first time you create an object of that class or when you access any static member. You don't call it yourself; the system calls it behind the scenes. This ensures that static data is ready and consistent for all users of the class.

💻

Example

This example shows a class with a static constructor that sets a static field. The static constructor runs once before the first use of the class.

csharp
using System;

class ExampleClass
{
    public static int StaticValue;

    // Static constructor
    static ExampleClass()
    {
        StaticValue = 100;
        Console.WriteLine("Static constructor called.");
    }

    public void ShowValue()
    {
        Console.WriteLine($"StaticValue = {StaticValue}");
    }
}

class Program
{
    static void Main()
    {
        Console.WriteLine("Program started.");
        ExampleClass obj1 = new ExampleClass();
        obj1.ShowValue();

        ExampleClass obj2 = new ExampleClass();
        obj2.ShowValue();
    }
}
Output
Program started. Static constructor called. StaticValue = 100 StaticValue = 100
🎯

When to Use

Use a static constructor when you need to initialize static data or perform actions that should happen only once for the entire class. For example, setting up configuration values, initializing static resources, or logging the first use of a class.

This is helpful when your static members depend on complex setup or external data that must be ready before use.

Key Points

  • A static constructor has no access modifiers and no parameters.
  • It runs automatically once before the class is used.
  • You cannot call it directly.
  • It is used to initialize static members.
  • If no static constructor is defined, static members can be initialized inline.

Key Takeaways

A static constructor initializes static members once before the class is used.
It runs automatically and cannot be called directly.
Use it to prepare static data or resources needed by the class.
Static constructors have no parameters and no access modifiers.
They help ensure static members are ready before any access.