Lazy Initialization

Lately I have been reading through some of the .Net Framework Advanced Development techniques and found an interesting subject called Lazy Initialization. This has been supported from .Net Framework Version 4.0 onwards.

Well, Lazy initialization is nothing but deferring the creation of an object until it is first used.

Syntax: Lazy<T>

Example of a basic Lazy initialization,

Lazy<Students> vStudents = new Lazy<Students>();

If there is no delegate passed in the Lazy<T> constructor, Activator.CreateInstance will be used to create the wrapped type when the object value is accessed for the first time. We should have a default constructor in the above scenario or else run time exception will be thrown.

When we have an resource expensive object in our system which has to be loaded based on the user demands then in such cases this Lazy Initialization will be more helpful.

By using this technique we shall improve the startup performance of the program by deferring initialization of the objects that are not required until the required objects have been created.