Click here to Skip to main content
13,090,170 members (57,337 online)
Click here to Skip to main content
Add your own
alternative version

Tagged as

Stats

102.2K views
1.4K downloads
55 bookmarked
Posted 3 Nov 2011

Lazy Loading in C#

, 3 Nov 2011
Rate this:
Please Sign up or sign in to vote.
Lazy loading is a design pattern that helps a developer to delay initialization of an object until the program actually needs the object.

Introduction

The “Lazy Loading” design pattern actually equips the developer with the art of providing data only when a property is called for. In other words, it is a on-demand loading. It is an efficient technique to improve performance.

Using the code

For the explanation, I have taken a simple scenario. Say we have classes PersonalLoan and Loan, as shown below.

public class PersonalLoan 
{ 
    public string AccountNumber { get; set; }
    public string AccounHolderName { get; set; }
    public Loan LoanDetail { get; set; }       
    public PersonalLoan(string accountNumber)
    {
        this.AccountNumber = accountNumber;
        this.AccounHolderName = getAccounHolderName(accountNumber);
    } 
}
public class Loan
{
    public string AccountNumber { get; set; }
    public float LoanAmount { get; set; }
    public bool IsLoanApproved { get; set; }
    public Loan(string accountNumber)
    { 
        Console.WriteLine("loan class constructor called.....");
        this.AccountNumber = accountNumber;
        this.LoanAmount = 1000;
        this.IsLoanApproved = true;
        Console.WriteLine("loan object created.....");
    }
}

For explanation's sake, we will assume that AccountNumber and AccounHolderName are not so costly operations in terms of memory occupation and time consumption. On the other hand, LoanDetail is a costly operation and is not used so often. So while designing a class, we may expect that it is better not to have the detail and to populate it when the object property “LoadDetail” is accessed. Please note that the PersonalLoan constructor does not load the LoanDetail property right this point.

In order to archive LazyLoading, we need to change our code a little and it should look like:

public class PersonalLoan
{ 
    private Loan _loanDetail;
    public string AccountNumber { get; set; }
    public string AccounHolderName { get; set; }
    public Loan LoanDetail 
    { 
        get { return _loanDetail ?? (_loanDetail = new Loan(this.AccounNumber)); }
    }
    public PersonalLoan(string accountNumber)
    {
        this.AccounNumber = accountNumber;
        this.AccounHolderName = getAccounHolderName(accountNumber);
    }
} 

In this way, we make sure that “LoanDetail” will be populate only when the property is called rather than when the object for “PersonalLoan” is instantiated. For details, please check PersonalLoan.cs in the attached project.

Now taking this a step ahead, let's look what .NET 4.0 has in this respect. 4.0 introduces a “Lazy<T>” class to support lazy initialization, where “T” specifies the type of object that is being lazily initialized. This is a new feature of C# 4.0 and it can be used when we are working with large objects. The implementation is quite similar to what we have done in the last example.

public class PersonalLoanLazyClass
{
    private readonly Lazy<Loan> lazyLoan;
    public string AccountNumber { get; set; }
    public string AccounHolderName { get; set; }
    public Loan LoanDetail
    {
        get { return this.lazyLoan.Value; }
    }        
    public PersonalLoanLazyClass(string accountNumber)
    {
        Console.WriteLine("PersonalLoanLazyClass Object Initializ: call to costructor....");
        this.AccountNumber = accountNumber;
        this.AccounHolderName = getAccounHolderName(accountNumber);
        this.lazyLoan = new Lazy<Loan>(() => new Loan(this.AccountNumber));
        Console.WriteLine("Completed initialization.......");
    }
}

For details, please check PersonalLoanLazyClass.cs in the attached project. You can check out lazy loading by adding the following lines of code to the executing program:

static void Main(string[] args)
{
    var personalLoan = new PersonalLoanLazyClass("123456789");
    Console.WriteLine("\n\n.......................Press Enter " + 
            "to continue.......................\n\n");
    Console.Read();
    Console.WriteLine(personalLoan.LoanDetail.LoanAmount.ToString());
    Console.Read();
    Console.Read();
}

Output:

output.png

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

No Biography provided

You may also be interested in...

Comments and Discussions

 
QuestionWhy to use lazy initialization in above code? Pin
sivatronics2-Sep-15 21:32
membersivatronics2-Sep-15 21:32 
GeneralMy vote of 3 Pin
_Noctis_1-Aug-14 14:42
professional_Noctis_1-Aug-14 14:42 
QuestionFew months agao I explain lazy loading there. Pin
S. M. Ahasan Habib3-Dec-13 0:51
professionalS. M. Ahasan Habib3-Dec-13 0:51 
GeneralMy vote of 1 Pin
tbayart26-Sep-13 0:55
membertbayart26-Sep-13 0:55 
QuestionWORST Article in the internet Pin
Kicha Parameshwara Ekanta Raniyar15-Jun-13 8:10
memberKicha Parameshwara Ekanta Raniyar15-Jun-13 8:10 
GeneralMy vote of 5 Pin
zenwalker19857-Nov-11 16:36
memberzenwalker19857-Nov-11 16:36 
GeneralMy vote of 5 Pin
Priyanka Paul4-Nov-11 18:47
memberPriyanka Paul4-Nov-11 18:47 
GeneralMy vote of 5 Pin
Priyanka Paul4-Nov-11 18:43
memberPriyanka Paul4-Nov-11 18:43 
GeneralMy vote of 4 Pin
smcilwain3-Nov-11 11:03
membersmcilwain3-Nov-11 11:03 
GeneralMy vote of 1 Pin
ashved3-Nov-11 6:40
memberashved3-Nov-11 6:40 
QuestionGreat Work Pin
Abinash Bishoyi3-Nov-11 6:32
memberAbinash Bishoyi3-Nov-11 6:32 
QuestionWhy not use Lazy<T> from .net 4.0? Pin
André Ziegler3-Nov-11 4:32
memberAndré Ziegler3-Nov-11 4:32 
AnswerRe: Why not use Lazy from .net 4.0? Pin
sheitman803-Nov-11 4:38
membersheitman803-Nov-11 4:38 
GeneralRe: Why not use Lazy from .net 4.0? Pin
Jerry Bian9-Dec-12 22:55
memberJerry Bian9-Dec-12 22:55 
GeneralMy vote of 5 Pin
wvd_vegt3-Nov-11 4:26
memberwvd_vegt3-Nov-11 4:26 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.170813.1 | Last Updated 3 Nov 2011
Article Copyright 2011 by Suprabhat Paul
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid