Sunday, May 29, 2011

Being Lazy in .NET 4.0

Lazy<T> is a new class available in .NET 4.0 which simplifies Lazy Initialization.

http://en.wikipedia.org/wiki/Lazy_initialization

The basic idea is that a field isn't initialized until it's used.

In earlier versions of .NET this could be done by using a field and property in conjunction. If the field is null, the property initializes the field and returns it. If the field isn't null, the property just returns the field.
Bitmap _backBitmap = null;
Bitmap BackBitmap
{
get
{
if(_backBitmap == null)
{
_backBitmap = new Bitmap("background.jpg");
}

return _backBitmap;
}
}


Lazy<T> provides an easier way to accomplish this.

Lazy<Bitmap> BackBitmap
= new Lazy<Bitmap>( () => new Bitmap("background.jpg") );


Lazy<T> uses the type specified between the <> and its constructor takes in a Lambda Expression which returns the value to which the field is initialized.

If you're not familiar with Lambda Expressions, they're just a way of creating an inline function.

You can read more about them here:
http://blogs.msdn.com/b/ericwhite/archive/2006/10/03/lambda-expressions.aspx
http://www.codeproject.com/KB/cs/explore_lamda_exp.aspx
http://msdn.microsoft.com/en-us/library/bb397687.aspx

I'll probably do a post about them in the future too.

No comments:

Post a Comment