I'd like to use Lazy T to implement memoization but the initialization function appears to require a static context.
For example, the following code refuses to compile, warning that non-static members a and b are inaccessible. It's not clear to me why this is so as the Lazy object is an instance member itself and has no visibility in a static context.
public class SomeExpensiveCalculation { private int a; private int b; public Lazy<int> Result = new Lazy<int>(() => a + b); //nope! }
By default, Lazy<T> objects are thread-safe. That is, if the constructor does not specify the kind of thread safety, the Lazy<T> objects it creates are thread-safe.
The Lazy<T> object ensures that all threads use the same instance of the lazily initialized object and discards the instances that are not used.
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.
Object initializers outside a constructor (or method) has to refer to static members only. This is because the instance hasn't been constructed until the constructor is run, hence the fields are not "ready yet" and therefor cannot be referenced. Static fields work because they are initialized before fields.
Note that the error isn't caused by Lazy<T>
, it is caused by the lambda expression. The workaround (and proper way of doing this) is to initialize Result
in a constructor.
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