C# Language Singleton Implementation Lazy, thread-safe Singleton (using Lazy)

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

Example

.Net 4.0 type Lazy guarantees thread-safe object initialization, so this type could be used to make Singletons.

public class LazySingleton
{
    private static readonly Lazy<LazySingleton> _instance =
        new Lazy<LazySingleton>(() => new LazySingleton());
 
    public static LazySingleton Instance
    {
        get { return _instance.Value; }
    }

    private LazySingleton() { }
}

Using Lazy<T> will make sure that the object is only instantiated when it is used somewhere in the calling code.

A simple usage will be like:

using System;
                    
public class Program
{
    public static void Main()
    {
        var instance = LazySingleton.Instance;
    }
}

Live Demo on .NET Fiddle



Got any C# Language Question?