Understanding Static Constructors in C#

Understanding Static Constructors in C#

In C#, a static constructor is a special constructor used to initialize static members of a class or perform actions that need to happen only once, for the entire type rather than per instance.

 

What Is a Static Constructor?

A static constructor 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.

Syntax:

static ClassName()

{

    // Initialization code here

}

 

Key Characteristics

  • Declared with static keyword
  • No parameters are allowed
  • No access modifiers (it is always private implicitly)
  • Executed automatically, once per type
  • Cannot be called directly
  • Useful for initializing static fields or performing one-time setup

 

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

 

Use Cases

  • Initializing static fields
  • Setting up configuration or environment data at the class level
  • Ensuring one-time setup before class usage
  • Connecting to external resources or caching mechanisms

 

Difference: Static vs Instance Constructor

Feature

Static Constructor

Instance Constructor

Invocation Time

First time class is used

Each time an object is created

Parameters

Not allowed

Allowed

Access Modifiers

Not allowed (always private)

Allowed

Manual Invocation

Not possible

Can be called with new

 

Summary

Static constructors in C# are powerful tools for ensuring that static data and logic are initialized once, automatically, and in a thread-safe manner. They are especially valuable when there is a need to prepare a class for use before any members—static or instance—are accessed.

 

Comments

Popular posts from this blog

Promises in Angular

Mastering Your Angular Workflow: Essential CLI Commands for Efficient Development

Observables in Angular