Thursday 22 May 2014

C# Lazy Initialization or Instantiation

Introduction: 

Sometime we want to defer or delay the initialization of the resource intensive or large object in case if it is not required at the moment to improve the performance or response time of the application.
Microsoft C# 4.0 introduced new feature Lazy<T> to achieve the above behavior. 

Lazy<T> defers or delay the creation of a large or resource-intensive object, or the execution of a resource-intensive task. It creates the instance of the object when it is first time used or called in the application.

Lazy<T> Properties:


It has 2 properties
  • IsValueCreated: It is boolean type property which return true if object is instanciated and false if not.
  • Value: It returns the object of type T.

Now I am going to create one sample application to demonstrate how to use it.

Step 1. Create one C# Console LazyInitialization application.
Step 2. Open the Program file and add below 2 classes inside the same namespace.


  public class Order

    {
       public Order()
      {
         this.OrderId=1234;
         this.DeliveryDate = DateTime.Today;
         this.OrderCreationDate = DateTime.Today.AddDays(-2);
      }

        public int OrderId { get; set; }


        public DateTime DeliveryDate { get; set; }        

        public DateTime OrderCreationDate { get; set; }
    
    }
    public class Customer
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public Lazy<Order> OrderInformation { get; set; }
    }



Customer class has an aggregation with Order. 
Initialization of the Order object will be deferred and it will only get initialized when it will be demanded first time in the application.

Now update the main method as shown below


 static void Main(string[] args)
        {
            Customer customer = new Customer();
            customer.FirstName = "Joe";
            customer.LastName = "Mackenzy";           
            customer.OrderInformation = new Lazy<Order>(); 

            Console.WriteLine("Customer Name:{0}", customer.FirstName + " " + customer.LastName);
            Console.WriteLine("Customer's Order isCreated: {0}", customer.OrderInformation.IsValueCreated);

            var customerOrder = customer.OrderInformation.Value;

            Console.WriteLine("Customer's Order isCreated: {0}", customer.OrderInformation.IsValueCreated);
            Console.WriteLine("Customer's Order ID: {0} Delivery Date: {1}", customerOrder.OrderId, customerOrder.DeliveryDate);
            Console.Read();
        }



it will output as  below








Primitive DataType:

Below I am going to illustrate for int data type.

 static void Main(string[] args)
        {
            int z = 0;
           
            Lazy<int> lazyint = new Lazy<int>(() => { z = 10; return z; });
            Console.WriteLine(string.Format("Value of z: {0}", z));
            var zValue = lazyint.Value;
            Console.WriteLine(string.Format("Value of z: {0}", zValue));
            Console.Read();

        }

In the above program z is an integer type variable with value 0. 
now z is initialized with Lazy object and inside anonymous method value of z is set to 10 which is a parameter of Lazy constructor.

so value of z is set to 10 after referring Value property of lazyint when it is being actually used. 

Output:
Value of z: 0
Value of z: 10.



Note: Refer MSDN for multithread usage.












No comments:

Post a Comment