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.
- File -> New Project
- Select C# -> Console Application
- Name as LazyObjectInstantiation, press OK
- Create the new class named Article
Declare three public members in that as follows:
-
- public class Article
- {
- public string Author { get; set; }
- public string ArticleName { get; set; }
- public string Language { get; set; }
- }
- Create a new class named AllArticles.
Declare public members and a constructor in that as follows:
-
- public class AllArticles
- {
-
- private Article[] allArticles = new Article[500];
- public AllArticles()
- {
-
- Console.WriteLine("Collectiong the Articles!");
- }
- }
- Create one more new class named Blogger.
Declare members and methods for that as follows:
-
- public class Blogger
- {
-
- public void Add() { }
- public void Update() { }
- public void Delete() { }
- public void Read() { }
-
- private AllArticles allArticles = new AllArticles();
- public AllArticles GetAllArticles()
- {
-
- return allArticles;
- }
- }
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.
- Write some functionality for object instantiation in the Program class file.
- class Program
- {
- static void Main(string[] args)
- {
- Console.WriteLine("***** Lazy Instantiation *****\n");
- Author auth = new Author();
- auth.Read();
- Console.ReadLine();
- }
- }
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:
-
- public class Blogger
- {
-
- public void Add() { }
- public void Update() { }
- public void Delete() { }
- public void Read() { }
-
- private AllArticles allArticles = new AllArticles();
- public AllArticles GetAllArticles()
- {
-
- return allArticles;
- }
- }
-
- With this,
-
- public class Blogger
- {
-
- public void Add() { }
- public void Update() { }
- public void Delete() { }
- public void Read() { }
-
- private Lazy<AllArticles> allArticles = new Lazy<AllArticles>();
- public AllArticles GetAllArticles()
- {
-
- return allArticles.Value;
- }
- }
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:
- class Program
- {
- static void Main(string[] args)
- {
- Console.WriteLine("***** Lazy Instantiation *****\n");
-
- Blogger blog = new Blogger();
- blog.Read();
-
- Blogger newBlog = new Blogger();
- AllArticles allArticles = newBlog.GetAllArticles();
- Console.ReadLine();
- }
- }
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.