Reader Level:
Articles

Lazy Initialization in .NET 4.0

By Amit Patel on July 11, 2012
Lazy initialization of an object means that its creation is deferred until it is first used.
  • 0
  • 0
  • 6367
Download Files:
 

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.

Amit Patel

I am  C# Corner MVP in Q2 2012.  I have 10 years of experiences in Microsoft technologies. I am very much passionate about Web technology. My core skill is ASP.NET, WCF, C#, JQuery and CSS.

COMMENT USING

Trending up