Mid SOLID

How do you implement a thread-safe Singleton in .NET?

One common thread-safe implementation uses lazy initialization with Lazy<T>:

public sealed class Singleton

private static readonly Lazy<Singleton> instance = new

Lazy<Singleton>(() => new Singleton());

private Singleton() { }

public static Singleton Instance => instance.Value;

This approach ensures thread safety and lazy initialization without locks.

More from Design Patterns in C#

All questions for this course