Lazy Initailization in .NET 4.0


Lazy initialization or lazy instantiation means that an object is not created until it is first referenced. Lazy initialization is used to reduce wasteful computation, memory requirements. Following is an example where Lazy initialization is particularly useful.

We have Department Object that has a Managers Property which is an array of all the managers in the department. To initialize Managers object we need a database connection. In the normal scenario Managers property will be initialized each time Department object is created. But by using lazy initialization we can defer the creation of the Managers Property (which is an array of Manager Objects) till the time it is actually referenced in code. We can declare Managers property like Lazy<Manager> to defer the creation of Manager Objects.

Another scenario where it is useful is:

Suppose we have several objects that are initialized on application startup we can defer the creation of objects that are not required immediately by using Lazy initialization and initialize only the required objects.

We can use Lazy<T> to do lazy initialization which also support thread-safety and exception propagation.

Lazy Initialization Example

To lazy initialize a type MyType use Lazy<MyType>.If we do not pass any delegate to the Lazy<T> constructor the wrapped type is created using the default constructor when we access the value property for the first time otherwise the constructor referenced by the passed delegate is invoked.

On first access, the wrapped type is created and returned, and stored for any future access.

After the Lazy object is created, no instance of object is created until the value property of the Lazy variable is accessed for the first time. On first access, the wrapped type is created and returned, and stored for any future access. In the following example we have a Manager class that is Lazy Initialized.

Lazy<Manager> _manager = new Lazy<Manager>();
Console.WriteLine(_manager); //Manager object is null
_manager.Value.Id="10";
_manager.Value.Name = "ashish";          
Console.WriteLine(_manager);//Manager object is initialized now
Console.Read(); 

    class Manager
    {
        string _name;
        public string Name
        {
            get { return _name; }
            set { _name = value; }
        }
        string _id;
        public string Id
        {
            get { return _id; }
            set { _id = value; }
        }
    }

Output Window

1.gif

We can also pass a delegate in the Lazy<T> constructor that invokes the constructor at object creation time that performs the required initialization steps at object creation time.

Lazy<Manager> _manager = new Lazy<Manager>(()=>new Manager(10));

erver'>