[ACCEPTED]-Lazy initialization in .NET 4-.net-4.0

Accepted answer
Score: 69

The purpose of the Lazy feature in .NET 4.0 15 is to replace a pattern many developers 14 used previously with properties. The "old" way 13 would be something like

private MyClass _myProperty;

public MyClass MyProperty
{
    get
    {
        if (_myProperty == null)
        {
            _myProperty = new MyClass();
        }
        return _myProperty;
    }
}

This way, _myProperty only gets 12 instantiated once and only when it is needed. If 11 it is never needed, it is never instantiated. To 10 do the same thing with Lazy, you might write

private Lazy<MyClass> _myProperty = new Lazy<MyClass>( () => new MyClass());

public MyClass MyProperty
{
    get
    {
        return _myProperty.Value;
    }
}

Of 9 course, you are not restricted to doing 8 things this way with Lazy, but the purpose is 7 to specify how to instantiate a value without 6 actually doing so until it is needed. The 5 calling code does not have to keep track 4 of whether the value has been instantiated; rather, the 3 calling code just uses the Value property. (It 2 is possible to find out whether the value 1 has been instantiated with the IsValueCreated property.)

Score: 10

"Lazy initialization occurs the first 8 time the Lazy.Value property is accessed 7 or the Lazy.ToString method is called.

Use 6 an instance of Lazy to defer the creation 5 of a large or resource-intensive object 4 or the execution of a resource-intensive 3 task, particularly when such creation or 2 execution might not occur during the lifetime 1 of the program."

http://msdn.microsoft.com/en-us/library/dd642331.aspx

Score: 9

Check out msdn documentation over here : Lazy Initialization

Lazy 5 initialization of an object means that its 4 creation is deferred until it is first used. Lazy 3 initialization is primarily used to improve 2 performance, avoid wasteful computation, and 1 reduce program memory requirements.

More Related questions