Pass parameters to constructor, when initializing a lazy instance

Xaqron picture Xaqron · Dec 11, 2010 · Viewed 22.4k times · Source
public class myClass
{
   public myClass(String InstanceName)
   {
      Name = InstanceName;
   }
   public String Name { get; set; }
}

// Now using myClass lazily I have:

Lazy<myClass> myLazy;
Console.WriteLine(myLazy.Value.Name);

My question is how to pass InstanceName to myClass constructor when we are using a lazy instance ?

Answer

Mark Byers picture Mark Byers · Dec 11, 2010

Try this:

Lazy<myClass> myLazy = new Lazy<myClass>(() => new myClass(InstanceName));

Remember that the expression is evaluated lazily, so if you change the value of the variable InstanceName before the constructor is called it might not do what you expect.