Make the frequent cases fast and the rare case correct

C# – Thread safe, Lazy Initialized [.NET 4.0 Lazy(T)] , Generic Singleton

Implementing a thread safe lazy initialized singleton has been made easy through .NET 4.0 release and introduction of Lazy(Of T) Class.

In this article Jon Skeet Author of C# in Depth explains in detail the various versions of implementing a singleton.

The below implementation is a small modification of this code from Judith Bishop’s book C# 3.0 Design Patterns.

By default, all public and protected members of the Lazy(Of T) class are thread safe and may be used concurrently from multiple threads. These thread-safety guarantees may be removed optionally and per instance, using parameters to the type’s constructors. – Lazy(Of T) MSDN.

Jon Skeet in his article lists the four characteristics of a Singleton:
A single constructor, which is private and parameterless. This prevents other classes from instantiating it (which would be a violation of the pattern). Note that it also prevents subclassing – if a singleton can be subclassed once, it can be subclassed twice, and if each of those subclasses can create an instance, the pattern is violated. The factory pattern can be used if you need a single instance of a base type, but the exact type isn’t known until runtime.

The class is sealed. This is unnecessary, strictly speaking, due to the above point, but may help the JIT to optimise things more.

A static variable which holds a reference to the single created instance, if any.

A public static means of getting the reference to the single created instance, creating one if necessary.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

//  Singleton Pattern Judith Bishop Dec 2006 - Slight modification
namespace GenericLazySingleton
    public class Singleton<T> where T : class, new()
        Singleton() { }

        private static readonly Lazy<T> instance = new Lazy<T>(() => new T());

        public static T UniqueInstance
            get { return instance.Value; }

    class Test1 { }
    class Test2 { }

    class Program

        static void Main()
            Test1 t1a = Singleton<Test1>.UniqueInstance;
            Test1 t1b = Singleton<Test1>.UniqueInstance;

            if (t1a == t1b)
                Console.WriteLine("Objects are the same instance");


Objects are the same instance

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: