Creating Lazy<T> - Singleton Class
Lazy<T> provides support for Lazy Initialization.
By Lazy Intialisation we mean that an object is not intialised until it is actually used. Below, I have shown how we can combine the Lazy<T> with the Singleton Pattern.
public sealed class LazySingleton
{
// Private object with lazy instantiation
private static readonly Lazy<LazySingleton> instance =
new Lazy<LazySingleton>(
delegate
{
return new LazySingleton();
}
//thread safety first
, System.Threading.LazyThreadSafetyMode.ExecutionAndPublication);
private LazySingleton()
{
// no public default constructor
}
// static instance property
public static LazySingleton Instance
{
get { return instance.Value; }
}
}
Related ResourcesHere is a list of some other related resources: