What is Lazy Loading?
Lazy Loading is an important paradigm to defer initialization of an object until the point at which it is needed.
Why we need it?
For making Application to:
- Run faster
- Consume less memory
In this article, I’ll show how to implement Lazy Loading.
Let us create a class Company which contains two properties, CompanyName and Employees. We will initialize CompanyName in Company constructor and initialize Employees only when we need it.
- public class Company
- {
- public string CompanyName;
- public Lazy < List < Employee >> Employees = null;
- public Company()
- {
- CompanyName = "MNC";
- Employees = new Lazy < List < Employee >> (() => getEmployees());
- }
-
- public List < Employee > getEmployees()
- {
- List < Employee > Employees = new List < Employee >
- {
- new Employee
- {
- FirstName = "Sridhar", LastName = "Adusumilli"
- }, new Employee
- {
- FirstName = "Manas", LastName = "Mohapatra"
- }
- };
- return Employees;
- }
- }
-
- public class Employee
- {
- public string FirstName
- {
- get;
- set;
- }
- public string LastName
- {
- get;
- set;
- }
- }
Now, we will initialize Employees property by using cmp.Employees.Value.
- class Program
- {
- static void Main(string[] args)
- {
- Company cmp = new Company();
- Console.WriteLine(cmp.CompanyName);
- foreach(var item in cmp.Employees.Value)
- {
- Console.WriteLine(item.FirstName + " " + item.LastName);
- }
- Console.ReadLine();
- }
- }
Complete Code:
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- namespace SampleLazyLoading
- {
- class Program
- {
- static void Main(string[] args)
- {
- Company cmp = new Company();
- Console.WriteLine(cmp.CompanyName);
- foreach(var item in cmp.Employees.Value)
- {
- Console.WriteLine(item.FirstName + " " + item.LastName);
- }
- Console.ReadLine();
- }
- }
- public class Company
- {
- public string CompanyName;
- public Lazy < List < Employee >> Employees = null;
- public Company()
- {
- CompanyName = "MNC";
- Employees = new Lazy < List < Employee >> (() => getEmployees());
- }
-
- public List < Employee > getEmployees()
- {
- List < Employee > Employees = new List < Employee >
- {
- new Employee
- {
- FirstName = "Sridhar", LastName = "Adusumilli"
- }, new Employee
- {
- FirstName = "Manas", LastName = "Mohapatra"
- }
- };
- return Employees;
- }
- }
-
- public class Employee
- {
- public string FirstName
- {
- get;
- set;
- }
- public string LastName
- {
- get;
- set;
- }
- }
- }
Conclusion
We need to check carefully whether the values pertaining to property initialization has been called otherwise the application will be at a risk of null exception.