Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing a non-static member via Lazy<T> or any lambda expression

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.

like image 932
Sawan Avatar asked Dec 25 '12 09:12

Sawan


People also ask

What is Lazy T?

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.

Is Lazy T thread safe?

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.

What is lazy initialization in C#?

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.


1 Answers

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

like image 145
JleruOHeP Avatar answered Oct 08 '22 01:10

JleruOHeP