Lazy thread safe singleton for .NET 3.5 or older alternate implementation

suggest change

Because in .NET 3.5 and older you don’t have Lazy<T> class you use the following pattern:

public class Singleton
{
    private Singleton() // prevents public instantiation
    {
    }

    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();
    }
}

This is inspired from Jon Skeet’s blog post.

The instance lives on the private nested class, so reading other members of Singleton does not initialize it. Privacy only hides Nested.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents