Singleton with System.Lazy

A Singleton class is one where there is only ever one instance of the class created. This means that constructors must be private to avoid users creating their own instances, and a static property (or method in languages without properties) is defined that returns a single static instance.

This is the most basic singleton, notice the key features:

  1. Static readonly field that contains the one and only instance.
  2. Constructor is private so it can only be called by the class itself.
  3. Static property that returns the single instance.

Looks like it satisfies, right? There’s just one (potential) problem. C# gives you no guarantee of when the static field _instance will be created. This is because the C# standard simply states that classes (which are marked in the IL as BeforeFieldInit) can have their static fields initialized any time before the field is accessed. This means that they may be initialized on first use, they may be initialized at some other time before, you can’t be sure when.

So what if you want to guarantee your instance is truly lazy. That is, that it is only created on first call to Instance?

First option is to use lazy construction ourselves, but being that our Singleton may be accessed by many different threads, we’d need to lock it down.

This is a standard double-check algorithm so that you don’t lock if the instance has already been created. However, because it’s possible two threads can go through the first if at the same time the first time back in, you need to check again after the lock is acquired to avoid creating two instances.

Second option is to take advantage of the C# standard’s BeforeFieldInit and define your class with a static constructor. It need not have a body, just the presence of the static constructor will remove the BeforeFieldInit attribute on the class and guarantee that no fields are initialized until the first static field, property, or method is called.

Third option is to use .Net 4.0 new features, System.Lazy type which guarantees thread-safe lazy-construction. Using System.Lazy, we get:

Note, you need your lambda to call the private constructor as Lazy’s default constructor can only call public constructors of the type passed in (which we can’t have by definition of a Singleton). But, because the lambda is defined inside our type, it has access to the private members so it’s perfect.

Lazy has many other uses as well, obviously, but I really love how elegant and readable it makes the lazy Singleton.