Static Constructor

Static Constructor:

In C#, a static constructor is used to initialize the static members of a class.

  • Automatic Invocation: Called automatically when the class is first accessed or when any static member or method is called. No explicit call is needed.

  • No Parameters: Cannot take parameters to ensure automatic invocation without requiring external data or arguments.

  • Single Execution: Executed only once per application domain, making it useful for initialization that should happen only once during the program's lifetime.

  • Implicitly Private: Always private, even if not explicitly defined, and cannot be called directly from outside the class.

  • Exception Handling: If an exception occurs, it prevents the class from being used, throwing a TypeInitializationException on subsequent attempts.

  • Thread Safety: Ensured by the runtime, guaranteeing execution only once, even with multiple threads accessing the class.

  • Static Scope: Cannot access instance members or methods, as it is designed to initialize static members only.


public class ExampleClass
{
    // Static member
    private static int staticField;

    // Static constructor
    static ExampleClass()
    {
        staticField = 42; // Initialize static members
        Console.WriteLine("Static constructor called.");
    }

    // Instance constructor
    public ExampleClass()
    {
        Console.WriteLine("Instance constructor called.");
    }
}

// Usage
class Program
{
    static void Main()
    {
        // First access, triggers static constructor
        var obj1 = new ExampleClass();
        
        // Subsequent access, static constructor won't be called again
        var obj2 = new ExampleClass();
    }
}

Comments

Popular posts from this blog

Multiline to singleline IN C# - CODING

EF Core interview questions for beginners

EF Core interview questions for experienced