I was reading this article by Jon Skeet.
In one the samples, he talks about using Lazy<T>
to implement singleton pattern.
This is how the code looks:
public sealed class Singleton
{
private static readonly Lazy<Singleton> lazy =
new Lazy<Singleton>(() => new Singleton());
public static Singleton Instance { get { return lazy.Value; } }
private Singleton()
{
}
}
He does mention at the end
It also allows you to check whether or not the instance has been created yet with the IsValueCreated property, if you need that.
IsValueCreated
indicates whether the lazy object is initialized or not.
I am wondering to ensure this class remains Singleton (only one insteace is created), where and how I would use IsValueCreated property ?
IsValueCreated
.Lazy<T>
will do that for you, internally checking theValue
delegate has been executed and if so, just return the martialized value, not execute the delegate again. – DoublefacedValue delegate has been executed and if so, just return the martialized value, not execute the delegate again
– SpheroidFunc
that creates the instance of theSingleton
() => new Singleton()
. On the first access of theValue
property the delegate orFunc
will be executed, materializing the value which will then be remembered. Subsequent accessors ofValue
will get this value, and the delegate orFunc
will not be re-materialized. – Doublefaced