Lazy Type and Lazy Loading in .C#

Lazy type

  • C# 4.0 introduced Lazy type, for lazy loading.

Lazy loading

Lazy loading refers to creating and initializing of objects only when it is required for the first time. That means,
you can define the object whenever you wish to, but it actually gets created only when you access its method/property/function.

Benefits of Lazy loading

  • Improves the startup time of a C# application.
  • Better performance and memory optimization.

Code For implementation:

Example

With Default or non-parametrize constructor.

  1. class Clent  
  2. {  
  3.     int[] l_objNumberOfDoc ;  
  4.       
  5.     // Custructor   
  6.     public Client()  
  7.     {  
  8.     Console.WriteLine("Create instance of Client");  
  9.     l_objNumberOfDoc = new int[10];  
  10.     }  
  11.     public int NumberOfDoc  
  12.     {   get { return l_objNumberOfDoc.Length;} }  
  13. }  
  14.   
  15.   
  16.   
  17. class Program  
  18. {  
  19.     static void Main()  
  20.     {  
  21.     // Create Lazy., Instance will not create.  
  22.     Lazy<Client> lazy = new Lazy<Client>();  
  23.   
  24.     // Show that IsValueCreated is false.  
  25.        //IsValueCreated is the property of Lazy type, for gets a value that indicates whether instance been created or not for client.  
  26.     Console.WriteLine("IsValueCreated = {0}", lazy.IsValueCreated);  
  27.   
  28.     // Get the Value.  
  29.     // ... This executes Client(). means create instance of Client  
  30.     Client l_objClient = lazy.Value;  
  31.   
  32.     // Show the IsValueCreated is true.  
  33.     Console.WriteLine("IsValueCreated = {0}", lazy.IsValueCreated);  
  34.   
  35.     // The object can be used.  
  36.     Console.WriteLine("Length = {0}", l_objClient.NumberOfDoc);  
  37.     }  
  38. }