Lazy thread-safe Singleton using Lazy<T>
suggest change.NET 4 Lazy<T> guarantees thread-safe object initialization with its default constructor, so this type can 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;
}
}
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents