Static Constructors in .NET Core

Static Constructors in .NET Core

⚙️ Static Constructors in .NET Core

Static constructors in C# are designed to initialize the class itself, not instances. They're perfect for one-time setup of static fields, configuration, logging, and more.

๐Ÿ”น Syntax

public class MyClass
{
    public static int StaticField;

    static MyClass()
    {
        StaticField = 42;
        Console.WriteLine("Static constructor called.");
    }
}

๐Ÿ“Œ Key Characteristics

  • ✅ Called once per app lifetime (before any static or instance member access)
  • ✅ Automatically invoked by the CLR — you can't call it manually
  • ✅ Thread-safe by default
  • ✅ Cannot accept parameters

๐Ÿ’ก When is it Called?

  • ๐Ÿ”ธ When any static member is accessed
  • ๐Ÿ”ธ When an instance of the class is created

๐Ÿงช Example: Database Initialization

public class Database
{
    public static string ConnectionString { get; set; }
    public static int MaxConnections { get; set; }

    static Database()
    {
        ConnectionString = "Server=myServer;Database=db;User Id=user;";
        MaxConnections = 100;
        Console.WriteLine("Static constructor executed: Database initialized.");
    }
}

๐Ÿš€ Real-World Example with Lazy Initialization

public class ConnectionManager
{
    private static Lazy<ConnectionPool> _pool = new(() => new ConnectionPool());

    static ConnectionManager()
    {
        Console.WriteLine("ConnectionManager static constructor called.");
    }

    public static ConnectionPool GetConnectionPool() => _pool.Value;
}

public class ConnectionPool
{
    public ConnectionPool()
    {
        Console.WriteLine("ConnectionPool initialized.");
    }
}

This ensures the expensive object is created only when needed.

✅ Benefits

  • ๐Ÿ”น One-time Initialization: No repeated setup calls
  • ๐Ÿ”น Cleaner Code: Centralizes all static setup logic
  • ๐Ÿ”น Thread-Safe: No manual locks required
  • ๐Ÿ”น Lazy Evaluation: Combine with Lazy<T> for on-demand loading

⚠️ Limitations

  • ⚠️ No parameters allowed
  • ⚠️ Cannot be explicitly called
  • ⚠️ Should not perform complex or long-running operations
Best Practice: Avoid time-consuming operations in static constructors. Use Lazy<T> or defer initialization when possible.

๐Ÿ“Œ When to Use

  • ๐Ÿ›  Initializing static configuration or settings
  • ๐ŸŒ Setting up shared connections or service clients
  • ๐Ÿงช Preparing logging or analytics libraries

๐Ÿงพ Summary

Static constructors are a powerful way to configure shared state in .NET Core. They execute once, are safe in multithreaded environments, and keep initialization logic clean. Use them wisely to enhance performance and structure.

Comments

Popular posts from this blog

Promises in Angular

Debouncing & Throttling in RxJS: Optimizing API Calls and User Interactions

Comprehensive Guide to C# and .NET Core OOP Concepts and Language Features