Lazy<T>
is a class introduced in the .NET Framework 4.0 to initialize the object later on, i.e., allows to initialize object when we are going to utilize or assign value to the object.
To understand Lazy initialization, consider the below class:
public class Employee
{
public string Name { get; set; }
public int Salary { get; set; }
public string Address { get; set; }
public int Id { get; set; }
}
In the following code, I am using the Employee
class. As you can see, I have initialized the class to null
.
Employee emp1=null;
Console.WriteLine(emp1);
if(Condition)
{
if (emp1 == null)
emp1 = new Employee();
}
In the above code, I am initializing class when I need it rather than initializing before using it same way we can do in the Singleton design pattern. By this way, we are lazing initializing the object and consume memory when we need it rather than initializing it in the first line of the method.
But now, .NET 4.0 Framework provides the new class to do this thing easily. The class is Lazy<T>
. So the above code is something as below:
Lazy<employee> emp = new Lazy<employee>();
Console.WriteLine(emp);
emp.Value.Id = 1;
emp.Value.Name = "pranay";
emp.Value.Salary = 123;
emp.Value.Address = "Ahmedabad";
Console.WriteLine(emp);
Output of the program is as follows:

As you can see in the output window, in its display, no value is defined.
Important Properties
Object gets created when we access property Value
and assign value to it. To find out the details, I used reflector which shows that the object gets created when I access property.

Another important property is IsValueCreated
- Gets a value that indicates whether a value has been created for this Lazy<t>
instance.
CodeProject