Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 453
Xaqron Avatar asked Dec 11 '10 00:12

Xaqron


People also ask

How do you initialize a Lazy?

Implementing a Lazy-Initialized Property To implement a public property by using lazy initialization, define the backing field of the property as a Lazy<T>, and return the Value property from the get accessor of the property. The Value property is read-only; therefore, the property that exposes it has no set accessor.

What is lazy initialization in C++?

In computer programming, lazy initialization is the tactic of delaying the creation of an object, the calculation of a value, or some other expensive process until the first time it is needed. It is a kind of lazy evaluation that refers specifically to the instantiation of objects or other resources.

What is Lazy <> in C#?

Lazy initialization is a technique that defers the creation of an object until the first time it is needed. In other words, initialization of the object happens only on demand. Note that the terms lazy initialization and lazy instantiation mean the same thing—they can be used interchangeably.

What is lazy loading in C# with example?

Lazy loading is essential when the cost of object creation is very high and the use of the object is vey rare. So, this is the scenario where it's worth implementing lazy loading. The fundamental idea of lazy loading is to load object/data when needed.


2 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.

like image 92
Mark Byers Avatar answered Sep 22 '22 02:09

Mark Byers


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

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

like image 26
ibrahim durmus - redmond Avatar answered Sep 24 '22 02:09

ibrahim durmus - redmond