Singleton in C# - The Lazy way

C-Sharp Sep 21, 2014

As developers, we have all created and used Singleton at times. It is one of the best-known patterns in software development.
Singleton pattern restricts the instantiation of a class to one object. This is useful when exactly one object is needed to coordinate actions across the system.

There are many ways to implement a Singleton Pattern in C#:

  • Using private and parameterless constructor. Here the instantiation is not performed until an object asks for an instance.
  • Using sealed class and let .net framework decide when to create the instance
  • A public static variable to hold the reference to the single created instance and create one if required.

Each method has its advantages/disadvantages and requires a deeper level of understanding how objects are created, destroyed, and behave throughout its lifecycle.

.net 4.0 provides an easy yet complete implementation to create Singleton class. It utilizes System.Lazy type for implementation.
As described on MSDN

Lazy initialization of an object means that its creation is deferred until it is first used. (For this topic, the terms lazy initialization and lazy instantiation are synonymous.) Lazy initialization is primarily used to improve performance, avoid wasteful computation, and reduce program memory requirements.

A sample singleton implementation with Lazy looks as follows:

public sealed class Singleton
    private Singleton()
    private static readonly Lazy<Singleton> lazy = new Lazy<Singleton>(() => new Singleton());
    public static Singleton Instance
            return lazy.Value;

Advantages of this approach

  • It is guaranteed thread safe.
  • Using Lazy type simplifies lazy object construction.
  • Provides a consistent exception propagation policy