Lazy initialization

Starting with .Net 4.0 framework, Microsoft has added support for lazy initialization.

The idea behind lazy initialization is that the creation of an object should be delayed until the first time it is needed.

In order to lazy initialize objects you can use the generic class Lazy<T> found in System namespace.

In the example below a Lazy<Data> object is instantiated and it receives a reference factory delegate. The factory delegate will be executed only when the first call to the Value get property of the Lazy<T> will be made.

using System;

class Program
{
    static void Main(string[] args)
    {
        var lazy = new Lazy<Data>(() => new Data());

        Console.WriteLine("Lazy created");
        Console.WriteLine(lazy.Value);
        Console.WriteLine(lazy.Value);
    }
}

class Data
{
    public Data()
    {
        Console.WriteLine("Data Constructor");
    }

    public override string ToString()
    {
        return "Data ToString";
    }
}

The execution result of the code above is:

Lazy created
Data Constructor
Data ToString
Data ToString
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s