This function returns two different values depending on the way its called. I understand that Closures close over variables, not over values and I expected the values returned from the second call to be the same regardless of how the function is called
static Func<int, int,int> Sum()
{
var test = 1;
return (op1, op2) =>
{
test = test + 1;
return (op1 + op2) + test;
};
}
Here is the call:
var mFunc = Sum();
Console.WriteLine("Calling Sum(1,1) with Invoke() " + Sum().Invoke(1, 1));
Console.WriteLine("Calling Sum(2,2) with Invoke() " + Sum().Invoke(2, 2));
Console.WriteLine("Calling mFunc(1,1)" + mFunc(1, 1));
Console.WriteLine("Calling mFunc(2,2)" + mFunc(2, 2));
Console.Read();
The result of using Invoke:
4
6
The result of using assigned variable:
4
7
Why does using Invoke changes the closures behavior?