Click here to Skip to main content
15,885,757 members
Articles / Programming Languages / C#

Lazy Loading in C#

Rate me:
Please Sign up or sign in to vote.
4.53/5 (26 votes)
3 Nov 2011CPOL2 min read 141.1K   1.6K   55   15
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.

C#
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:

C#
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.

C#
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:

C#
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)


Written By
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionWhy to use lazy initialization in above code? Pin
sivatronics2-Sep-15 21:32
sivatronics2-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
professionaltbayart26-Sep-13 0:55 
QuestionWORST Article in the internet Pin
Kicha Parameshwara Ekanta Raniyar15-Jun-13 8:10
Kicha Parameshwara Ekanta Raniyar15-Jun-13 8:10 
GeneralMy vote of 5 Pin
zenwalker19857-Nov-11 16:36
zenwalker19857-Nov-11 16:36 
GeneralMy vote of 5 Pin
Priyanka Paul4-Nov-11 18:47
Priyanka Paul4-Nov-11 18:47 
GeneralMy vote of 5 Pin
Priyanka Paul4-Nov-11 18:43
Priyanka Paul4-Nov-11 18:43 
GeneralMy vote of 4 Pin
Steve Mcilwain3-Nov-11 11:03
Steve Mcilwain3-Nov-11 11:03 
GeneralMy vote of 1 Pin
ashved3-Nov-11 6:40
ashved3-Nov-11 6:40 
QuestionGreat Work Pin
Abinash Bishoyi3-Nov-11 6:32
Abinash Bishoyi3-Nov-11 6:32 
QuestionWhy not use Lazy<T> from .net 4.0? Pin
André Ziegler3-Nov-11 4:32
André Ziegler3-Nov-11 4:32 
Why don't you use the class from .net Framework 4.0?
http://msdn.microsoft.com/en-us/library/dd642331%28VS.100%29.aspx[^]
'A programmer is just a tool which converts caffeine into code'

AnswerRe: Why not use Lazy from .net 4.0? Pin
sheitman803-Nov-11 4:38
sheitman803-Nov-11 4:38 
GeneralRe: Why not use Lazy from .net 4.0? Pin
Jerry Bian9-Dec-12 22:55
Jerry Bian9-Dec-12 22:55 
GeneralMy vote of 5 Pin
wvd_vegt3-Nov-11 4:26
professionalwvd_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.