How do you implement a thread-safe Singleton pattern in modern C# using Lazy<T>?
Short answer
Lazy defers creation of the instance until it's first accessed AND guarantees thread-safe initialization by default, making it the cleanest modern way to implement a Singleton without manually writing double-checked locking.
Advertisement
AModel answer
Lazy<T> defers creation of the instance until it's first accessed AND guarantees thread-safe initialization by default, making it the cleanest modern way to implement a Singleton without manually writing double-checked locking.
public class ConfigManager {
private static readonly Lazy<ConfigManager> _instance = new(() => new ConfigManager());
public static ConfigManager Instance => _instance.Value;
private ConfigManager() { }
}Real-world example
Ensuring a single, shared application configuration or logging instance across the entire application.
Likely follow-ups
- Why is a plain 'static readonly' field alone not always sufficient to guarantee thread-safe lazy initialization?
Related topics