SIGN UP MEMBER LOGIN:    
ARTICLE

Lazy Initailization in .NET 4.0

Posted by Ashish Shukla Articles | .NET 4.5 May 17, 2010
Lazy initialization or lazy instantiation means that an object is not created until it is first referenced. Lazy initialization is used to reduce wasteful computation, memory requirements. Following is an example where Lazy initialization is particularly useful.
Reader Level:

Lazy initialization or lazy instantiation means that an object is not created until it is first referenced. Lazy initialization is used to reduce wasteful computation, memory requirements. Following is an example where Lazy initialization is particularly useful.

We have Department Object that has a Managers Property which is an array of all the managers in the department. To initialize Managers object we need a database connection. In the normal scenario Managers property will be initialized each time Department object is created. But by using lazy initialization we can defer the creation of the Managers Property (which is an array of Manager Objects) till the time it is actually referenced in code. We can declare Managers property like Lazy<Manager> to defer the creation of Manager Objects.

Another scenario where it is useful is:

Suppose we have several objects that are initialized on application startup we can defer the creation of objects that are not required immediately by using Lazy initialization and initialize only the required objects.

We can use Lazy<T> to do lazy initialization which also support thread-safety and exception propagation.

Lazy Initialization Example

To lazy initialize a type MyType use Lazy<MyType>.If we do not pass any delegate to the Lazy<T> constructor the wrapped type is created using the default constructor when we access the value property for the first time otherwise the constructor referenced by the passed delegate is invoked.

On first access, the wrapped type is created and returned, and stored for any future access.

After the Lazy object is created, no instance of object is created until the value property of the Lazy variable is accessed for the first time. On first access, the wrapped type is created and returned, and stored for any future access. In the following example we have a Manager class that is Lazy Initialized.

Lazy<Manager> _manager = new Lazy<Manager>();
Console.WriteLine(_manager); //Manager object is null
_manager.Value.Id="10";
_manager.Value.Name = "ashish";          
Console.WriteLine(_manager);//Manager object is initialized now
Console.Read(); 

    class Manager
    {
        string _name;
        public string Name
        {
            get { return _name; }
            set { _name = value; }
        }
        string _id;
        public string Id
        {
            get { return _id; }
            set { _id = value; }
        }
    }

Output Window

1.gif

We can also pass a delegate in the Lazy<T> constructor that invokes the constructor at object creation time that performs the required initialization steps at object creation time.

Lazy<Manager> _manager = new Lazy<Manager>(()=>new Manager(10));

erver'>
Login to add your contents and source code to this article
share this article :
post comment
 
6 Months Free & No Setup Fees ASP.NET Hosting!
Become a Sponsor
PREMIUM SPONSORS
  • Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
    ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications. Visit DynamicPDF here
6 Months Free & No Setup Fees ASP.NET Hosting!
Become a Sponsor