What is lazy initialization. here is the code i got after search google.
class MessageClass
{
public string Message { get; set; }
public MessageClass(string message)
{
this.Message = message;
Console.WriteLine(" *** MessageClass constructed [{0}]", message);
}
}
Lazy<MessageClass> someInstance = new Lazy<MessageClass>(
() => new MessageClass("The message")
);
Why should I create an object in this way?
When actually we need to create object in this way?
The purpose of the
Lazyfeature in .NET 4.0 is to replace a pattern many developers used previously with properties. The “old” way would be something likeThis way,
_myPropertyonly gets instantiated once and only when it is needed. If it is never needed, it is never instantiated. To do the same thing withLazy, you might writeOf course, you are not restricted to doing things this way with
Lazy, but the purpose is to specify how to instantiate a value without actually doing so until it is needed. The calling code does not have to keep track of whether the value has been instantiated; rather, the calling code just uses theValueproperty. (It is possible to find out whether the value has been instantiated with theIsValueCreatedproperty.)