Monday, July 15, 2013

4 Ways to Implement Lazy Loading in C#


Implementing the Lazy Loading design pattern in your application comes in handy when you're dealing with large quantities of objects.


Let's imagine that some data is provided to you by a database or by a service, and let's suppose that you're going to work with objects that have a huge amount of related objects.

Loading all of them in one fell swoop when your application starts may significantly hurt performances.
What if you could load those objects only when you actually need them? That's what Lazy Loading is for.

Using the Code

There are 4 main ways through which you can implement the Lazy Loading pattern:
  • Lazy Initialization
  • Virtual Proxies
  • Value Holders
  • Ghost Objects
Lazy Initialization

The Lazy Initialization technique consists in checking the value of a class's field when it's being accessed: if that value equals null, the field gets loaded with the proper value before it is returned.
Here is an example:

    public class Customer
        public int CustomerID { get; set; }
        public string Name { get; set; }
        private IEnumerable<Order> _orders;
        public IEnumerable<Order> Orders
                if (_orders == null)
                    _orders = OrdersDatabase.GetOrders(CustomerID);
                return _orders;
        // Constructor
        public Customer(int id, string name)
            CustomerID = id;
            Name = name;

Pretty simple, isn't it? However, there's actually an alternative method through which we can accomplish the same goal.

Read more: Codeproject
QR: Inline image 1