Lazy Initialization in .NET 4.0

Lazy initialization of an object means that its creation is deferred until it is first used. (For this topic, the terms lazy initialization and lazy instantiation are synonymous.) Lazy initialization is primarily used to improve performance, avoid wasteful computation, and reduce program memory requirements. 

Here is the sample code:
 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

 

namespace LazySample

{

    classCustomer

    {

        publicint Id { get;set; }

        publicstring Name { get;set; }

        public Customer(int Id, string Name)

        {

            this.Id = Id;

            this.Name = Name;

        }

 

    }

    classProgram

    {

 

 

        staticvoid Main(string[] args)

        {

            Lazy<Customer> cust =new Lazy<Customer>(() => new Customer(1,"Amit"));

            DisplayCustomer(cust.Value);

 

 

        }

        publicstatic void DisplayCustomer(Customer c)

        {

            Console.WriteLine(c.Id.ToString());

            Console.WriteLine(c.Name.ToString());

        }

    }

}


If you debug the above code you can see how the constructor calls and sets the value when the DisplayCustomer Method is called.
 
Happy Coding.