Object on Demand is also called Lazy loading pattern, Lazy loading delays the initialization of object. This is a new feature of C# 4.0 and can be used when we are working with large objects when it is not in use. This article will explain you about "Lazy" class.
Suppose we have Candidate class and EducationProfile class. One candidate can have more than one EducationProfile (like: Bachelors (BBA), Master(MBA)). If you want to show the EducationProfile with the respective Candidate, you need to load EducationProfiles associated with that Candidate. If you are loading an Education Profile with the respective candidate you need to initialize a Candidate object and that is supposed to be huge .
For avoiding the situation you can use the Lazy Loading Pattern. Loading of EdutioanProfile will only happen when you will use EducationProfile list. And this will make sure fast action in comparison to the normal one and performance will also increase.
Explaining an example of Candidate and EducationProfile relationship by Lazy loading:
First we need to create classes of Candidate and EducationProfile.
- public class EducationProfile
- {
- public int Id { get; set; }
- public string Digree { get; set; }
- public DateTime PassingYear { get; set; }
- }
-
-
-
- public class Candiate
- {
- public string Name { get; set; }
- public int EducationProfileId { get; set; }
- public List GetAllEducationProfile()
- {
- return educationProileList.value;
- }
-
- Lazy<list<educationproile>> educationProileList;
-
- public Candiate(string name, int id)
- {
-
- Name = name;
- EducationProfileId = id;
- educationProileList = new Lazy<list<educationproile>>(() => { return GetEducationProfileList(id); });
-
- }
-
- private List GetEducationProfileList(int id)
- {
-
- List list = new List();
- Parallel.For(100, 110, (int i) =>
- {
- EducationProile educationprofile = new EducationProile();
- educationprofile.Id = i;
- list.Add(educationprofile);
- });
- return list;
- }
- }
- </list<educationproile></list<educationproile>
In the constructor of Candidate class, properties are initializing and declaring educationProileList object, which is the generic List of educationProile and filled by
GetEducationProfileList method. This method will only call when educationProileList object will be used. The following is the main method which shows the behavior of lazy loading:
- public static void Main(string[] args)
- {
- Candidate candidate = new Candidate("AnyName", 1);
- foreach(EducationProile eduProfile in candiate.GetAllEducationProfile())
-
- Console.WriteLine("Id:{0}",eduProfile.Id);
- Console.Read();
- }