Lazy Initializer to defer expensive Object creation

0 comments
.NET 2010 comes with lots of new features. Some relates to Technology while other relates to language enhancements. The huge class library that is there with .NET framework is also enriched with new classes. In .NET 4.0 there is a new set of classes which introduces a new concept called Lazy initializes. Here is a discussion how simply you can use Lazy initialize to defer the execution of a method or property for values to whenever it is required.

Introduction
It is true that we often use Lazy initializer in our code  by restricting the load of objects using Properties. Thus unless the property is called from the code, the object will not created. A sample of it is :
private List<string> lazystrings = null;
        public List<string> LazyStrings
        {
            get
            {
                if (this.lazystrings == null)
                    this.lazystrings = this.GetLazyStrings();
                return this.lazystrings;
            }
        }

        private List<string> GetLazyStrings()
        {
            List<string> lazystrings = new List<string>();
            for (int i = 0; i < 30; i++)
            {
                lazystrings.Add(string.Format("Item {0}", i));
            }
            return lazystrings;
        }

In this case we have wrapped the loading of a List inside a property and hence the object will be loaded only when the object calls the property.  This is very common scenario of our daily programming needs.
Microsoft introduces a new technique called LazyInitializer that enables to do this in the same way as we do with the code above, but Microsoft recommends to use Lazy instead as becausee it is ThreadSafe. In this article we will see how to implement Microsoft's Lazy initializers.

Lazy Initializers
Lets look how you can use Lazy intializers in .NET 4.0.

There are 3 types in .NET 4.0 which supports Lazy Initialization.
  1. Lazy : It is just a wrapper class that supports lazy initialization.
  2. ThreadLocal : It is the same as Lazy but the only difference is that it stores data on Thread Local basis.
  3. LazyInitializer : Provides static implementation of Lazy initializer which eliminates the overhead of creation of Lazy objects. 

0 comments: