C# Language Singleton Implementation Lazy, thread safe singleton (for .NET 3.5 or older, alternate implementation)

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

Example

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.

Because the Nested class is nested and private the instantiation of the singleton instance will not be triggered by accessing other members of the Sigleton class (such as a public readonly property, for example).



Got any C# Language Question?