Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why is Lazy<T> constrained to static contexts?

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! } 
like image 668
Daniel Schobel Avatar asked Jul 14 '11 07:07

Daniel Schobel


People also ask

Is Lazy static 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 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.

How does lazy initialization work?

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.

How does Lazy work C#?

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.


1 Answers

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.

like image 198
larsmoa Avatar answered Oct 13 '22 08:10

larsmoa