C# › Design Patterns in C#
How do you implement a thread-safe Singleton pattern in modern C# using Lazy<T>?
BeginnerAnswer
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.