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 ?
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.
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With