Lazy Initialization in .NET

Introduction

In this article, we will learn the basics of Lazy Initialization in .NET and how to implement it in our applications. A simple console application for Lazy Initialization. Using the following example you understand the concept of this Lazy<> class.

Console Application

To create the demo application for Lazy Initialization, use the following procedure. Assume you are writing a class that encapsulates the operations of a Blogger. In addition to the expected methods, such as Add (), Update (), Delete() and Read (), you also want to provide the ability to return a collection of Article objects (via a class named AllArticles), that represents every single Article from the database.

  1. File -> New Project
  2. Select C# -> Console Application
  3. Name as LazyObjectInstantiation, press OK
  4. Create the new class named Article

    Declare three public members in that as follows:
    1. //Represents a single article  
    2.     public class Article  
    3.     {  
    4.         public string Author { getset; }  
    5.         public string ArticleName { getset; }  
    6.         public string Language { getset; }  
    7.     } 
  5. Create a new class named AllArticles.

    Declare public members and a constructor in that as follows:
    1. //Represents All Articles of Blogger  
    2.     public class AllArticles  
    3.     {  
    4.         // Here maximum articles are 500  
    5.         private Article[] allArticles = new Article[500];  
    6.         public AllArticles()  
    7.         {  
    8.           //Assume we fill up the array of Article objects   here.  
    9.             Console.WriteLine("Collectiong the Articles!");  
    10.         }  

  6. Create one more new class named Blogger.

    Declare members and methods for that as follows:

    1. //The Blogger has-an AllArticles object.  
    2.     public class Blogger  
    3.     {  
    4.         // Assume these methods do something useful.  
    5.         public void Add() { /* New Article */ }  
    6.         public void Update() { /* Update Article */ }  
    7.         public void Delete() { /* Delete the article */ }  
    8.         public void Read() { /* Read Articles */ }  
    9.   
    10.         private AllArticles allArticles = new AllArticles();  
    11.         public AllArticles GetAllArticles()  
    12.         {  
    13.             // Return all of the articles.  
    14.             return allArticles;  
    15.         }  

    The current implementation of Blogger makes the assumption that the object user will want to obtain a list of articles via the GetAllArticles() method. The AllArticles member variables will still be allocated, thereby creating 500 Article objects in memory.

  7. Write some functionality for object instantiation in the Program class file.
    1. class Program  
    2.     {  
    3.         static void Main(string[] args)  
    4.         {  
    5.             Console.WriteLine("***** Lazy Instantiation *****\n");         
    6.             Author auth = new Author();  
    7.             auth.Read();  
    8.             Console.ReadLine();  
    9.         }  
    10.     } 

Here, you would rather not create 500 objects that nobody will use, since that will add a good deal of stress to the .NET garbage collector. While you could manually add some code to ensure the allArticles object is created only if used, there is an easier way.

Lazy<> Class

The Lazy object instantiation is not just useful to decrease allocation of unnecessary objects. You can also use this technique if a given member has an expensive creation code, such as invoking a remote method, communication with a relational database.

The base class libraries provide a very useful generic class named Lazy<>, defined in the System namespace of mscorlib.dll. This class allows you to define data that will not be created unless your code base actually makes use of it. Since this is a generic class, you must specify the type of item to be created on.

For the first use it can be any type with the .NET base class libraries. To enable Lazy Instantiation of all the Article member variables, you can simply replace this:

  1. //The Blogger has-an AllArticles object.  
  2. public class Blogger  
  3. {  
  4.     // Assume these methods do something useful.  
  5.     public void Add() { /* New Article */ }  
  6.     public void Update() { /* Update Article */ }  
  7.     public void Delete() { /* Delete the article */ }  
  8.     public void Read() { /* Read Articles */ }  
  9.   
  10.     private AllArticles allArticles = new AllArticles();  
  11.     public AllArticles GetAllArticles()  
  12.     {  
  13.         // Return all of the articles.  
  14.         return allArticles;  
  15.     }  
  16. }  
  17.   
  18. With this,  
  19. // The Blogger has-an Lazy<AllArticles> object.  
  20. public class Blogger  
  21. {  
  22.     // Assume these methods do something useful.  
  23.     public void Add() { /* New Article */ }  
  24.     public void Update() { /* Update Article */ }  
  25.     public void Delete() { /* Delete the article */ }  
  26.     public void Read() { /* Read Articles */ }  
  27.   
  28.     private Lazy<AllArticles> allArticles = new Lazy<AllArticles>();  
  29.     public AllArticles GetAllArticles()  
  30.     {  
  31.         // Return all of the articles.  
  32.         return allArticles.Value;  
  33.     }         

Beyond the fact that we are now representing the AllArticles member variable as a Lazy<> type, notice that the implementation of the previous GetAllArticles() method has also been updated. Specifically, we must use the read-only Value property of the Lazy<> class to obtain the actual stored data.

The following updated Main() method will indirectly allocate the Song objects only if GetAllArticles() is called:

  1. class Program  
  2. {  
  3.     static void Main(string[] args)  
  4.     {  
  5.         Console.WriteLine("***** Lazy Instantiation *****\n");  
  6.         // No allocation of AllArticles object here!  
  7.         Blogger blog = new Blogger();  
  8.         blog.Read();  
  9.         // Allocation of AllArticles happens when you call GetAllArticles().  
  10.         Blogger newBlog = new Blogger();  
  11.         AllArticles allArticles = newBlog.GetAllArticles();  
  12.         Console.ReadLine();  
  13.     }  

Note: For detailed code please download the Zip file attached above.

Summary

Hopefully you can see the usefulness of the Lazy<> class. If you have any suggestion regarding this article then please contact me.

Up Next
    Ebook Download
    View all
    test-2
    Read by 1 people
    Download Now!
    Learn
    View all