January 26, 2012

Lazy<T>

Added in version 4.0 of .Net, a lazy template. The templated paramater object is not created until its value is first accessed.
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);
}

No comments: