Attention: We are retiring the ASP.NET Community Blogs. Learn more >

Lazy Loading Object Design pattern

Hi,

Some time when you are working with large objects where some of the data (properties in the object) is not required frequently, the use of Lazy loading is the best.

 Let’s say you have an Object which contains many properties along with a property for exposing long XML string. The long XML string is only required to be shown only a few times when you are also showing the details of the object. At this point when we are loading a list of this object to display (where by XML string will not be displayed) its not a good practice to also load the XML string in the object. Since this would take lots of extra Network bandwidth and memory space.

In these kinds of circumstances we can use the Lazy Loading Object relational pattern. In Lazy loading pattern the object is not inialized until it’s needed. There are many ways to Implement Lazy Loading.

One of the simple way of using Lazy loading is shown below

public class Category
{
    private int _CategoryId = 0;
    private int CategoryId
    {
        set { _CategoryId = value; }
        get { return _CategoryId; }
    }

    private string  _strXML = null;
    public string strXML
    {
        get
        {   

            //This is done for lazy Loading the XML String .
            if (_StrXML == null)
                _StrXML = StrXML.GetStrXMLByCategoryId(_CategoryId);
            return _StrXML;
        }
        set { _StrXML = value; }
    }
}

In the example given above, I am loading the strXML property only when it is being used. The property will not be loaded before that.

Regards
Vikram

1 Comment

  • I rather like this format instead (does the same thing):

    get { return _StrXML?? (_StrXML = StrXML.GetStrXMLByCategoryId(_CategoryId)); }

Comments have been disabled for this content.