Friday, March 8, 2013

C# in Depth: Implementing the Singleton Pattern

C# in Depth: Implementing the Singleton Pattern:

Table of contents (for linking purposes...)

Sixth version - using .NET 4's Lazy type

If you're using .NET 4 (or higher), you can use the System.Lazy type to make the laziness really simple. All you need to do is pass a delegate to the constructor which calls the Singleton constructor - which is done most easily with a lambda expression.
public sealed class Singleton
{
    private static readonly Lazy lazy =
        new Lazy(() => new Singleton());
   
    public static Singleton Instance { get { return lazy.Value; } }

    private Singleton()
    {
    }
}
It's simple and performs well. It also allows you to check whether or not the instance has been created yet with the IsValueCreated property, if you need that.

No comments: