Tuesday, January 14, 2014

Lazy Initialization in .NET

Lazy Initialization in .NET

This is the amazing feature that introduced with the .NET 4.0. This is mainly focuses following objectives.

1. Improve performance.
2. Avoid unnecessary computations.
3. Reduce unnecessary memory allocations.
4. Create objects when they are actually need.
5. Provide thread safe facility by framework.

This is very useful when you need create very expensive object when only you need to access members of these objects.

In here I will describe this Lazy initialization with following sample code.

I have created following class for the demonstration and created Order object as two types as lazy object and normal object.

public class Customer
{
        private readonly Lazy<Order> lazyOrder;
        private readonly Order order;

        public int Id { get; set; }
        public string Name { get; set; }

        public Order LazyOrder
        {
            get { return this.lazyOrder.Value; }
        }

        public Order Order
        {
            get { return this.order; }
        }

        public Customer()
        {
            lazyOrder = new Lazy<Order>();
            order = new Order();
        }
}

Following is the testing code for above code,

static void Main(string[] args)
{
    //Create customer object as lasy initialization
    Lazy<Customer> customerObject = new Lazy<Customer>(true);
    //Check whether customer object is actually created or not
    bool isCustomerCreated = customerObject.IsValueCreated;
    //Get the id of the customer
    int id= customerObject.Value.Id;
    //Check whether customer object is actually created after getting the customer Id
    bool isCustomerCreatedFinish = customerObject.IsValueCreated;
          
}

I’m going to initialize the Customer object as Lazy initialization. When you debug the code isCustomerCreated is always false until you need something from the Customer object.

isCustomerCreatedFinish is getting true after you actually access member within Customer object. (get the customer Id)

Also debug the Customer class constructor and there you can also notice until you call method/property inside the Order object it is not getting constructed but normal object will construct even you not call method/property inside order object.

Following is lazy Order object,

Following is normal Order object,