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; //1. Mark Employees property as Lazy
- public Company()
- {
- CompanyName = "MNC";
- Employees = new Lazy < List < Employee >> (() => getEmployees()); // 2. Asking the property to load values from getEmployees() method
- }
- //Method to get Employees.
- public List < Employee > getEmployees()
- {
- List < Employee > Employees = new List < Employee >
- {
- new Employee
- {
- FirstName = "Sridhar", LastName = "Adusumilli"
- }, new Employee
- {
- FirstName = "Manas", LastName = "Mohapatra"
- }
- };
- return Employees;
- }
- }
- //Employee Class which contains FirstName and LastName properties
- public class Employee
- {
- public string FirstName
- {
- get;
- set;
- }
- public string LastName
- {
- get;
- set;
- }
- }
- class Program
- {
- static void Main(string[] args)
- {
- Company cmp = new Company();
- Console.WriteLine(cmp.CompanyName);
- foreach(var item in cmp.Employees.Value) //3. When we call cmp.Employees.Value then only the Employee list will be populated.
- {
- Console.WriteLine(item.FirstName + " " + item.LastName);
- }
- Console.ReadLine();
- }
- }

SubashPosted Aug 21, 2016, 1:46 AM
Very nice work
Sridhar SharmaPosted Dec 28, 2015, 8:28 AM
Thanks :)
Manas MohapatraPosted Nov 25, 2015, 10:01 AM
Short and Elegant Blog
Upendra Pratap ShahiPosted Nov 23, 2015, 12:04 PM
nice share..