Understanding Static Constructors in C#

🧠 Introduction

A static constructor is used to initialize static fields or perform actions that should happen only once—at the class level.


πŸ“Œ What Is a Static Constructor?

It is declared using the static keyword and is called automatically by the .NET runtime before the first instance is created or any static members are accessed.

static ClassName()
{
    // Initialization code here
}

🧾 Key Characteristics

πŸ’» Code Example


using System;

public class MyClass
{
    public static int StaticValue;

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

    // Instance Constructor
    public MyClass()
    {
        Console.WriteLine("Instance constructor called");
    }
}

class Program
{
    static void Main()
    {
        Console.WriteLine(MyClass.StaticValue); // Triggers static constructor
        MyClass obj = new MyClass();            // Then calls instance constructor
    }
}
  
Output:
Static constructor called
100
Instance constructor called

πŸ“¦ Common Use Cases

⚖️ Static vs Instance Constructor

FeatureStatic ConstructorInstance Constructor
Invocation TimeFirst time class is usedEach time an object is created
ParametersNot allowedAllowed
Access ModifiersNot allowed (always private)Allowed
Manual InvocationNot possibleCan be called with new

πŸ“Œ Summary

Static constructors ensure static members are initialized once and safely. They help prepare a class before its members are accessed and are particularly useful in static configuration, caching, and logging scenarios.

Comments

Popular posts from this blog

Debouncing & Throttling in RxJS: Optimizing API Calls and User Interactions

Promises in Angular

Comprehensive Guide to C# and .NET Core OOP Concepts and Language Features