pavanarya

Let us share the knowledge

Lazy Class

leave a comment »

Hi,

In this post let us see the implementation and usage of the Lazy<T> class. Lazy<T> class was introduced in the .Net framework 4.0.

Let us assume that we are having a code piece that create some objects for different classes initially and then performs some IO operations and again some other task and at last it is going to make use of the objects that we created initially.

So it is waste of resources to create the objects at early stage and delayed cleaning of objects is also equally dangerous.

So in order to overcome these kind of issues Lazy class was introduced in .Net framework 4.0.

Lazy<T> is mainly used to delay the initialization of the object.
An object for a class is created only when we make use of the property “Value” .Let us take an example that implements Lazy class concept.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Lazy<LazyTest> tst = new Lazy<LazyTest>();
            bool isobjcreated = tst.IsValueCreated;
            if(!isobjcreated)
              {
                    Console.writeline ("Object for LazyTest class not yet created");
              }
            LazyTest t= tst.Value;
              if(isobjcreated)
              {
                    Console.writeline ("Object for LazyTest class created);
              }
            string str = t.consval;
            t.MyProperty = 20;
           int i= t.MyProperty;
            t.testmethod();
        }
    }
    class LazyTest
    {
        private int num;
        public string consval = "";
        public int MyProperty
        {
            get { 
                return num;
            }
            set {
                this.num = value;
            }
        }
        public void testmethod()
        {
            Console.WriteLine("Hai");
        }

        
    }
}

The output of above code:

object for LazyTest class not yet created.
object for lazyTest class created.
Hai

So let me explain the code:
In the main method initially we created an lazy object for LazyTest class using Lazy tst = new Lazy();
And this doesn’t actually create an object for the LazyTest class.
In the next step we are having tst.IsValueCreated. IsValueCreated property is used to determine whether an object is created or not for the Lazy instance ie whether the object is created for the class LazyTest or not.

In the next step we are having LazyTest t= tst.Value; The value property is used to get the initialized value for the Lazy instance . In other words the “value” property will create an object for the Class T that we specify in Lazy.
Now we can make use of the object returned by the “value” poperty in a regular way.

Lazy Class and a class with parameter constructor

In the above example we are having a not having a constructor in the class LazyTest. So if we don’t have a constructor then the compiler will be creating a default constructor with no parameters.
So let us create a class with a parameter constructor

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Lazy<LazyTest> tst = new Lazy<LazyTest>(
                //() => {
                //    LazyTest test=new LazyTest("hello");
                //    return test;
                //}
                );
            bool isobjcreated = tst.IsValueCreated;
            LazyTest t= tst.Value;
            string str = t.consval;
            t.MyProperty = 20;
           int i= t.MyProperty;
            t.testmethod();
        }
    }
    class LazyTest
    {
        private int num;
        public string consval = "";
        public int MyProperty
        {
            get { 
                return num;
            }
            set {
                this.num = value;
            }
        }
        public LazyTest(string a)
        {
            consval=a;
        }

        public void testmethod()
        {
            Console.WriteLine("Hai");
        }        
    }
}

Once we execute this code we will not have any compile time issues but at run time we will have an exception(System.MissingMemberException).
We will be getting this exception at tst.Value; The reason behind this is the tst object (Lazy tst) is just a reference to the wrapper created by the CLR and when we try to return the actual object of LazyTest class using tst.value it tries to create an object for the Lazy6Test class like new LazyTest(). But in our class LazyTest doesn’t have a parameter less constructor. Hence it throws an exception.
So does it mean we cannot create an object lazily for a class that is having a constructor with parameters. The answer is No.

So inorder to over come the above problem we can make use of this

public Lazy(
	Func<T> value
)

Here “Func valueFactory” is the delegate that returns a value of type T. And this delegate function is executed and it returns an object(LazyTest class object) that we want to create lazily when invoked using Lazy class value property.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Lazy<LazyTest> tst = new Lazy<LazyTest>(
                () => {
                    LazyTest test=new LazyTest("hello");
                    return test;
                }
                );
            bool isobjcreated = tst.IsValueCreated;
            LazyTest t= tst.Value;
            string str = t.consval;
            t.MyProperty = 20;
           int i= t.MyProperty;
            t.testmethod();
        }
    }
    class LazyTest
    {
        private int num;
        public string consval = "";
        public int MyProperty
        {
            get { 
                return num;
            }
            set {
                this.num = value;
            }
        }
        public LazyTest(string a)
        {
            consval=a;
        }

        public void testmethod()
        {
            Console.WriteLine("Hai");
        }        
    }
}


















About these ads

Written by pavanarya

November 27, 2011 at 10:16 am

Posted in Asp.net

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

Follow

Get every new post delivered to your Inbox.

Join 68 other followers

%d bloggers like this: