ARTICLE

Lazy Initialization in .NET 4.0

Posted by Amit Patel Articles | .NET 4.5 July 11, 2012
Lazy initialization of an object means that its creation is deferred until it is first used.
Reader Level:
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.

Login to add your contents and source code to this article
post comment
     
COMMENT USING
PREMIUM SPONSORS
Over-C is a holistic consortium of communications and technology specialists. We build, deploy and market both business as well as consumer products and solutions.
Join a Chapter
SPONSORED BY
  • PDF reports have never been easier to create. With our included WYSIWYG Designer, you can layout your reports, set up your data source and let DynamicPDF ReportWriter do the rest.