Mou
Mou

Reputation: 16282

Lazy initialization in .NET 4

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?

Upvotes: 33

Views: 26859

Answers (3)

Pranay Rana
Pranay Rana

Reputation: 176896

Check out msdn documentation over here : Lazy Initialization

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

Upvotes: 9

Andrew
Andrew

Reputation: 14447

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

private MyClass _myProperty;

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

This way, _myProperty only gets instantiated once and only when it is needed. If it is never needed, it is never instantiated. To 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 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 the Value property. (It is possible to find out whether the value has been instantiated with the IsValueCreated property.)

Upvotes: 72

asawyer
asawyer

Reputation: 17808

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

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

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

Upvotes: 10

Related Questions