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!
}
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 initializeResultin a constructor.