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
Post a Comment