I have a Main method like this:
static void Main(string[] args)
{
var b = new byte[1024 * 1024];
Func<double> f = () =>
{
new Random().NextBytes(b);
return b.Cast<int>().Average();
};
var avg = f();
Console.WriteLine(avg);
}
Since I am accessing a local variable b here the compiler creates a class to capture that variable and b becomes the field of that class. Then the b lives as long as the life time of the compiler generated class and it causes a memory leak. Even if b goes out of scope (maybe not in this situation but imagine this is inside of another method and not Main), the byte array won't be deallocated.
What I wonder is, since I am not accessing or modifying the b anywhere after declaring Func, why can't the compiler inline that local variable and not bother with creating a class? Like this:
Func<double> f = () =>
{
var b = new byte[1024 * 1024];
new Random().NextBytes(b);
return b.Cast<int>().Average();
};
I compiled this code in Debug and Release modes, the DisplayClass is generated in both:
Is this just not implemented as an optimization or is there anything I am missing?
