[ACCEPTED]-Lazy initialization in .NET 4-.net-4.0
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.)
"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."
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
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.