January 26, 2012

Lazy<T>

Added in version 4.0 of .Net, a lazy template. The concept of 'Lazy' programming is quite simple, do not create an object until you actually use it. Lazy has 2 properties, "IsValueCreated" and "Value". "IsValueCreated" specifies if the templated object has been created yet or not whilst "Value" when invoked actually creates an instance of the templated item.
Here is a simple example:

public class Thingey
{
    public string Name { get; set; }
}
To test it:
internal void TestLazyTemplate()
{
    Lazy<Thingey> myThingey = new Lazy<Thingey>();
    bool isCreated = myThingey.IsValueCreated;
    Debug.Assert(isCreated == false); // Not created yet
    myThingey.Value.Name = "Sutum";   // Created when accessed
    isCreated = myThingey.IsValueCreated; 
    Debug.Assert(isCreated == true);
}
This is a simple example but does not really show the power of Lazy. Fortuneately, NInject works with Lazy<> parameters. This is a sneaky way to implement late binding. I used this in a recent project to late bind some IPlugin interfaces. Some plugins were injected into a constructor as Lazy plugins. This means that when the constructor was invoked the plugins were not created immediately. It is only when the "plugins.Value" parameter is accessed that NInject actually constructed the plugins. In this case this did not happen in the constructor at all, it is invoked later in another separate "Initialise" method.