An Overview of C# Static Constructors

Static Constructor in C#

In C#, a static constructor is a special type of constructor that is used to initialize any static data or to perform a particular action that needs to be executed once when the class is loaded into memory, typically before any instance of the class is created, or any static members are accessed

  • Before the first instance of the class is created: This ensures that any static members (fields, methods) are initialized or prepared before they're used by an object of that class.
  • Before any static member of the class is referenced: This guarantees that the static initialization code runs before any static elements are accessed.

About Static constructors

  • It doesn't have access modifiers (like public, private, or protected) and can't have parameters.
  • It is implicitly private and can't be called directly by code.
  • A static constructor is called automatically before the first instance of the class is created or any static members are accessed.
  • Static constructors are called once per application domain, and they execute before any instance-level constructors. If a class is never used or referenced in the program, its static constructor will not execute

In a Simple way of understanding

  • Declared with the static keyword: This distinguishes them from regular instance constructors (which don't have the static keyword).
  • No access modifiers or parameters: Static constructors cannot have access modifiers (like public or private) or take parameters.
  • Implicit invocation: They are called automatically by the CLR (Common Language Runtime) at the appropriate time, and you cannot call them directly.

Usages of Static constructors

  • Initializing static fields: This is the primary purpose of static constructors. You can assign values to static fields within the constructor's body.
  • Performing one-time actions: If you have code that needs to be executed only once during the program's lifetime, a static constructor is a suitable place.
    • Loading configuration data from a file
    • Registering event handlers
    • Performing validation checks on type parameters (with some limitations)
  • One-time Setup: Perform one-time setup tasks such as setting up static resources or initializing static caches.
  • Singleton Pattern: In some cases, static constructors are used in conjunction with the singleton pattern to ensure that a class has only one instance.
  • Logging or Tracing Setup: Set up logging or tracing infrastructure for a class.

Sample Program

class MyStaticClass
{
    private static readonly int _age;

    public static int MemberAge
    {
        get
        {
            Console.WriteLine("i am refered MemberAge");
            return _age;
        }
    }

    private static readonly string _name;

    public static string MemberName
    {
        get
        {
            Console.WriteLine("i am refered MemberName");
            return _name;
        }
    }

    static MyStaticClass()
    {
        Console.WriteLine("i am called - Initialization of static data");
        _age = 42;
        _name = "Demo";
    }
}
 Console.WriteLine(" Main Started");
 Console.WriteLine(" Main Access MemberName Start");
 Console.WriteLine(MyStaticClass.MemberName);
 Console.WriteLine(" Main Access MemberName End");

 Console.WriteLine(" Main Access MemberAge Start");
 Console.WriteLine(MyStaticClass.MemberAge);
 Console.WriteLine(" Main Access MemberAge End");
 Console.WriteLine(" Main Ended");

 Console.ReadLine();

Result

 Main Started
 Main Access MemberName Start
i am called - Initialization of static data
i am refered MemberName
Demo
 Main Access MemberName End
 Main Access MemberAge Start
i am refered MemberAge
42
 Main Access MemberAge End
 Main Ended

Thanks


Similar Articles