I have a class that holds on to a delegate, in order to lazily evaluate something later.
Once I\'ve evaluated it, by calling the delegate, I clear out the reference
The "problem" is that the compiler is noticing that it can reuse a single delegate instance forever. It doesn't capture any context, not even the implicit this
reference. So this:
void CreateTestData(out WeakReference wr, out Lazy<int> l)
{
Func<int> f = () => 10;
...
}
Is turned into something like:
static Func<int> hiddenDelegate;
static int HiddenMethod()
{
return 10;
}
void CreateTestData(out WeakReference wr, out Lazy<int> l)
{
if (hiddenDelegate == null)
{
hiddenDelegate = HiddenMethod;
}
Func<int> f = hiddenDelegate;
...
}
Look at the code in ildasm (or Reflector with no optimization turned on) to see exactly what's going on.