I Love Being Lazy

As new versions of the .NET framework have been released, the common theme of many of the enhancements seems to be making the developer’s job easier. Today I’d like to talk about a new class released in the .NET 4.0 framework that does just that: Lazy<T>.

Lazy loading is a fairly common design pattern used to postpone loading a resource until it is needed.  This is not a new concept, and I’m sure code like this will look very familiar to many of you.


    private IEnumerable<Employee> employees;
    public IEnumerable<Employee> Employees
    {
        get
        {
            if (employees == null)
            {
                employees = GetEmployees();
            }
            return employees;
        }
    }
    privateIEnumerable<Employee> GetEmployees()
    {
        // Code to load employees here
    }


With the addition of the Lazy<T> class, this syntax can be simplified to the following.


private readonly Lazy<IEnumerable<Employee>> employees = 
new Lazy<IEnumerable<Employee>>(GetEmployees);

public IEnumerable<Employee> Employees
{
	get
		{
		return employees.Value;
		}
}

private static IEnumerable<Employee> GetEmployees()
{
    // Load employees here
}

When a Lazy<T> object is used, the contained object (accessed via the Value property) is initialized the first time either the Value property or the ToString() method is called.  The IsValueCreated property can be used to determine if the contained object has been initialized.

By default, when Lazy<T> objects are created, they are created to be thread safe.  In this thread safe mode (LazyThreadSafetyMode.ExecutionAndPublication), locks are used to ensure that only one thread can call the code that initializes the internal object.  This thread safety property can be overridden in the constructor.  There are two other thread safety modes: one which employs no thread safety (LazyThreadSafetyMode.None) and one where multiple threads are all allowed to run the initializer, but only the thread that completed first will be allowed to set the value (LazyThreadSafetyMode.PublicationOnly).

The constructor that I’ve most often used when I’ve used the Lazy<T> class takes a Func<T> parameter (Note:  this is the constructor used in the example above).  The function passed to the constructor is the function that will be used to initialize the contained object.  This can be as simple as the following.

private Lazy<List<string>> someStrings =
    new Lazy<List<string>>(() => new List<string>());

One important thing to keep in mind is that the Lazy<T> objects are immutable, so once you’ve created them, you can’t change them.  If needed, however, you can always reinitialize them to a new value.  So the following is not allowed.

someStrings.Value = new List<string>();

But the following is.

someStrings = new Lazy<List<string>>(() => new List<string>());

I hope this was helpful!  Happy, Lazy coding to you!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s