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

Sawan picture Sawan · Dec 25, 2012 · Viewed 10.8k times · Source

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.

Answer

JleruOHeP picture JleruOHeP · Dec 25, 2012

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