Private static readonly is today the preferred way to create a singleton in C#, but it don't have much laziness. You can implement it with a nested class, but with C#4 you can directly use the System.Lazy<T> class. Here is the model of the implementation:
public sealed class Singleton { private static readonly Lazy<Singleton> lazy = new Lazy<Singleton>(() => new Singleton()); public static Singleton Instance { get { return lazy.Value; } } private Singleton() { } }
Published under: Microsoft .NET Tips · · · ·