Pass Parameters to Constructor, When Initializing a Lazy Instance
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 ?

3 Answers

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.

1

Lazy has two ways to initialize. The first is using T's default ctor (parameterless)

the second is accepting an Func that has customer initialization logic. you should use the second overload as mentioned here

You can't, Lazy<T> requires a parameterless constructor. You could use the Lazy<T>(Func<T>) constructor though, with a method that initializes the class.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Maya Lin-Takahashi

Maya Lin-Takahashi

Consumer Tech & Gadget Reviewer

Maya is a hardware enthusiast who tests and reviews smart home devices, smartphones, wearables, and audio gear. She focuses on practical consumer value and build quality.

Share this article
Twitter Facebook Pinterest