Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[C#] Lazy Initialization Test (Lazy<T>)
#1
Here's a test snippet that I created to demonstrate a phenomena called "Lazy initialization".

Code:
private void MainMethod()
{
    Lazy<MyClass> mClass = LazyClass1; /* Choose LazyClass1 or LazyClass2 */

    Console.WriteLine();
    Console.WriteLine("[#] Value Created: {0}", mClass.IsValueCreated);
    Console.WriteLine("[#] Name: {0} [ID - {1}]", mClass.Value.Name, mClass.Value.ID);
    Console.WriteLine("[#] Value Created: {0}", mClass.IsValueCreated);
}

#region Lazy<T> Code

Lazy<MyClass> LazyClass1 = new Lazy<MyClass>(() => { return new MyClass() {
    ID = 1,
    Name = "AceInfinity"
}; });
Lazy<MyClass> LazyClass2 = new Lazy<MyClass>(() => { return new MyClass(); });

public class MyClass
{
    public int ID { get; set; }
    public string Name { get; set; }

    public MyClass() : this(0, "{Default}") { }

    public MyClass(int vID, string vName)
    {
        Console.WriteLine("[!] Constructor called for initialization...");

        ID = vID;
        Name = vName;
    }
}

#endregion

What's the point? If you run through my code above you'll see that only after the constructor is called that a Value is created for the Lazy<T>. What's the significance? It means that the constructor is only called for initialization when we try to use a value. We may consider this useful because now this enables us to save memory for the initialization through the constructor for this class until we actually need to use a value from the initialized class itself.

Great for optimization and performance reasons...

I give you 2 constructor overloads to play around with, and they can be called by either using LazyClass1 or LazyClass2 Lazy<MyClass> to define the mClass Lazy<MyClass>, but the default one is modified and chained to the other master constructor with 2 params so that I didn't have to write out the Console.Writeline() line in both constructors.

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


Messages In This Thread
[C#] Lazy Initialization Test (Lazy<T>) - by AceInfinity - 08-04-2012, 09:15 PM

Forum Jump:


Users browsing this thread: 2 Guest(s)