When should I use Lazy<T>?
Solution 1:
You typically use it when you want to instantiate something the first time its actually used. This delays the cost of creating it till if/when it's needed instead of always incurring the cost.
Usually this is preferable when the object may or may not be used and the cost of constructing it is non-trivial.
Solution 2:
You should try to avoid using Singletons, but if you ever do need to, Lazy<T>
makes implementing lazy, thread-safe singletons easy:
public sealed class Singleton
{
// Because Singleton's constructor is private, we must explicitly
// give the Lazy<Singleton> a delegate for creating the Singleton.
static readonly Lazy<Singleton> instanceHolder =
new Lazy<Singleton>(() => new Singleton());
Singleton()
{
// Explicit private constructor to prevent default public constructor.
...
}
public static Singleton Instance => instanceHolder.Value;
}