Software Architecture – C# 4.0 -New Feature – Lazy initialization

“Lazy initialization” is new concept in introduced in C# 4.0

If you have worked in OR Mapping technologies like linq 2 sql or nhibernate then you must be aware of concept called ”Lazy loading” which suggest that a object/collection as property in a object is not created till it is accessed in the code.

Similar is true for “Lazy initialization” which is provided with Lazy class at System.Lazy(Of T).
It proposes that an object is not created till it is used by the first time the Lazy(Of T).Value property is accessed or the Lazy(Of T).ToString method is called.

According to MSDN, “Lazy initialization” is basically used to:

Defer the creation of a large or resource-intensive object or the execution of a resource-intensive task, particularly when such creation or execution might not occur during the lifetime of the program.

Let see an example.

Suppose there is an object doing very heavy processing  going on in its constructor.

class HeavyWeightObject
    {

        public  HeavyWeightObject()
        {
Console.WriteLine("Constructor for HeavyWeightObject.. Doing a lot of processing..");
        }
    }

Let create and instance of this object as:

HeavyWeightObject hWO = new HeavyWeightObject();

You will notice that when the above line executes at the same time constructor for
HeavyWeightObject is called. So output will be as:

Constructor for HeavyWeightObject.. Doing a lot of processing..

That is normal behavior.
Lets try a twist in code as:

      Console.WriteLine("Lets analyse Lazy initilization .....");
      Console.WriteLine("Before Lazy  is created ..");
 Lazy<HeavyWeightObject> lHWO = new Lazy<HeavyWeightObject>( );
 Console.WriteLine("After Lazy  is created ..");
 Console.WriteLine("Acess Object " + lHWO.Value);

The output will look like as:



Notice that when line 3 executes, then constructor is not called, because of lazy initialization.
After that line no 4 executes, by printing the “After Lazy is created ..”
When line no 5 executes, .value property is accessed at this point, so is constructor called, this is because of lazy initialization.

Hope things are clear.

Enjoying coding in C# 4.0

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

%d bloggers like this: