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
- Declared with
statickeyword - No parameters are allowed
- Cannot have access modifiers (always implicitly private)
- Called automatically, once per type
- Cannot be called manually
- Used for initializing static members or 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
Static constructor called
100
Instance constructor called
π¦ Common Use Cases
- Initializing static fields
- Loading configuration data
- Setting up logging or database connections
- Caching static resources
⚖️ 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 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
Post a Comment