I have this code:
public class MyClass { public int X { get; set; } public int Y { get; set; } private Lazy<int> lazyGetSum = new Lazy<int>(new Func<int>(() => X + Y)); public int Sum{ get { return lazyGetSum.Value; } } }
Gives me this error:
A field initializer cannot reference the non-static field, method, or property.
I think it is very reasonable to access a non-static member via lazy, how to do this?
* EDIT *
The accepted answer solves the problem perfectly, but to see the detailed and in-depth -as always- reason of the problem you can read Joh Skeet's answer.
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.
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.
Lazy initialization of an object means that its creation is deferred until it is first used. (For this topic, the terms lazy initialization and lazy instantiation are synonymous.) Lazy initialization is primarily used to improve performance, avoid wasteful computation, and reduce program memory requirements.
You can move it into constructor:
private Lazy<int> lazyGetSum; public MyClass() { lazyGetSum = new Lazy<int>(new Func<int>(() => X + Y)); }
See @JohnSkeet answer below for more details about the reason of the problem. Accessing a non-static member via Lazy<T> or any lambda expression
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