Understanding and Using Static Constructors in C#: One-Time Initialization

Learn about static constructors in C# and how they're used for one-time initialization of static members. This tutorial provides a clear explanation with examples, demonstrating their use in setting up shared resources and performing initial setup tasks for a class.



Understanding Static Constructors in C#

What is a Static Constructor?

In C#, a static constructor is a special constructor used to initialize static members (fields, properties, events) of a class. It's called automatically only once, the very first time the class is accessed (either by creating an instance or referencing a static member). Static constructors are particularly useful for performing one-time setup tasks or initializing shared resources for the class.

Key Points about Static Constructors

  • No Modifiers or Parameters: Static constructors cannot have access modifiers (`public`, `private`, etc.) or parameters.
  • Implicit Invocation: The static constructor is called automatically; you can't explicitly call it.
  • Initialization: It's primarily used to initialize static fields of the class. It's also used for tasks that need to be done only once, like setting up database connections.

Example: Using a Static Constructor

This example shows how to initialize a static field using a static constructor. The static constructor (`static Account()`) initializes the `rateOfInterest` field when the `Account` class is first used. The `Main()` method creates two instances of the class, demonstrating that the static field has the same value for both objects because it is initialized only once.

C# Code

using System;

public class Account {
    public int id;
    public string name;
    public static float rateOfInterest; 

    public Account(int id, string name) {
        this.id = id;
        this.name = name;
    }

    static Account() {
        rateOfInterest = 9.5f;
    }

    public void Display() {
        Console.WriteLine($"{id} {name} {rateOfInterest}");
    }
}

public class Example {
    public static void Main(string[] args) {
        Account a1 = new Account(101, "Sonoo");
        Account a2 = new Account(102, "Mahesh");
        a1.Display();
        a2.Display();
    }
}

Conclusion

Static constructors in C# provide a mechanism for performing one-time initialization of static members. This is a useful feature, particularly when working with shared resources or performing setup tasks before any instances of a class are created.