I came across some code that confused me a little and I'd like to know what's going on behind the scenes to make this possible.
The code in question was a unit test using the FakeItEasy library. ReturnsLazily()
and Invokes()
methods were being used, both of which accept lambda functions as parameters. Both the lambda functions were either referencing/changing a local variable. When these lambdas are invoked is it not possible the local variables they reference have been garbage collected?
I've tried to illustrate what I mean with a simple similar example below:
class Program
{
static void Main(string[] args)
{
var (PrintLocals, ModifyLocals) = GenerateFunctions();
// Here I am able to print and modify the local variables declared in GenerateFunctions
PrintLocals();
ModifyLocals();
PrintLocals();
ModifyLocals();
PrintLocals();
}
public static (Action, Action) GenerateFunctions()
{
var someObject = new object();
var someNumber = 1;
void PrintLocals()
{
Console.WriteLine(someObject.GetHashCode());
Console.WriteLine(someNumber);
}
void ModifyLocals()
{
someObject = new object();
someNumber += 1;
}
return (PrintLocals, ModifyLocals);
}
}
The output when run is:
58225482
1
54267293
2
18643596
3
Clearly the local variables I declared in the GenerateFunctions()
method still exists somewhere as I am able to modify/print them. Where are these local variables being stored and when can the be GC?