C sharp - Static Constructor in C#
What is a Static Constructor?
A static constructor is a special constructor used to initialize static members of a class. It is called automatically once only, when the class is accessed for the first time.
Key Features
-
Has no parameters.
-
Cannot be called explicitly.
-
Automatically called once per type, not per object.
-
Used to initialize static fields or perform any one-time setup.
Syntax
class ClassName
{
static ClassName()
{
// Initialization code for static fields
}
}
Simple Example
using System;
class AppConfig
{
public static string version;
// Static constructor
static AppConfig()
{
version = "1.0.0";
Console.WriteLine("Static constructor called");
}
public static void ShowVersion()
{
Console.WriteLine("App Version: " + version);
}
}
class Program
{
static void Main()
{
// First access triggers the static constructor
AppConfig.ShowVersion();
}
}
Output:
Static constructor called
App Version: 1.0.0