What is lazy initialization of objects? How do you do that and what are the advantages?
//Lazy instantiation delays certain tasks.
//It typically improves the startup time of a C# application.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace LazyLoad
{
class Program
{
static void Main(string[] args)
{
Lazy MyLazyClass = new Lazy(); // create lazy class
Console.WriteLine("IsValueCreated = {0}",MyLazyClass.IsValueCreated); // print value to check if initialization is over
MyClass sample = MyLazyClass.Value; // real value Creation Time
Console.WriteLine("Length = {0}", sample.Length); // print array length
Console.WriteLine("IsValueCreated = {0}", MyLazyClass.IsValueCreated); // print value to check if initialization is over
Console.ReadLine();
}
}
class MyClass
{
int[] array;
public MyClass()
{
array = new int[10];
}
public int Length
{
get
{
return this.array.Length;
}
}
}
}
// out put
// IsValueCreated = False
// Length = 10
// IsValueCreated = True