Lazy

Quite often in singleton classes you might find yourself doing the standard plumbing code like this:

private static MyClass _current = new MyClass();

public static MyClass Current {
get { return _current; }
}

or a bit simpler with C# 7:

public static MyClass Current = new MyClass();

If class is a bit heavier (e.g. using lots of memory) you might do it lazily with a lock:

private static MyClass _current;

public static MyClass Current {
get {
lock(SyncRoot) {
if (_current == null) { _current = new MyClass(); }
return _current;
}
}
}

What almost never gets any love is Lazy construct known from .NET Framework 4:

private static Lazy<MyClass> _current = new Lazy<MyClass>();

public static MyClass Current {
get { return _current.Value; }
}

This will initialize class on the first access, it is tread safe by default, and you can even use custom initializer if needed, e.g.:

private static Lazy<MyClass> _current = new Lazy<MyClass>(() => new MyClass(42));

public static MyClass Current {
get { return _current.Value; }
}

Exactly what doctor prescribed. :)

PS: And stop using double-check locking.

Leave a Reply

Your email address will not be published. Required fields are marked *