Showing posts with label Lazy. Show all posts
Showing posts with label Lazy. Show all posts

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.

March 4, 2011

Immediate/Lazy Execution Terms

Deferred execution and eager evaluation

Immediate Execution - means that the computation/execution is done in the function and finished once the function return. (Fully eager evaluation as most C# code does)
Deferred/Eager Execution (buffering) - means that most of the work will be done on the first MoveNext() or when the IEnumerator instance is created (For IEnumerable it is when GetEnumerator is called)
Deferred/Lazy Exceution (streaming) - means that the work will be done each time GetNext() is called but nothing before.