Sunday, November 03, 2013

C# Singleton Pattern by Jon Skeet

C# in Depth: Implementing the Singleton Pattern

Thread safety without locks

public sealed class Singleton {
    private static readonly Singleton instance = new Singleton();
    // Explicit static constructor to tell C# compiler           
    // not to mark type as beforefieldinit
    static Singleton() { }
    private Singleton() { }
    public static Singleton Instance { get { return instance; } }
}

Fully lazy instantiation:
public sealed class Singleton {
    private Singleton() { }
    public static Singleton Instance { get { return Nested.instance; } }
    private class Nested  {
        // Explicit static constructor to tell C# compiler
        // not to mark type as beforefieldinit
        static Nested() { }
        internal static readonly Singleton instance = new Singleton();
    }
}

C# in Depth: Articles
Cover of C# in Depth

C# Design Strategies - @ pluralsight

No comments: