Is lazy instantiation about using less code but getting the same result? Surely this is generally a good thing to do (providing making the code to short / efficient doesn’t damage readability/maintainability).
Please refer to this lazy instantiation:
public sealed class Singleton
{
private Singleton()
{
}
public static Singleton Instance { get { return Nested.instance; } }
private class Nested
{
// Explicit static constructor to tell C# compiler
// not to mark type as beforefieldinit
static Nested()
{
}
internal static readonly Singleton instance = new Singleton();
}
}
There is no private property of Instance (I know it’s implicit) – is it that which makes it lazy – the fact we don’t have a setter within the public static Singleton Instance property?
Lets say we have a field of a type that is expensive to construct
The problem with this code is that instansiating
Fooincurs the performance cost of instansiatingExpensive– whether-or-not theExpensivefield is ever accessed. The obvious answer is to construct the instance on demand or lazily instansiate the field:This is lazy instansiation.