I read with an interesting article called Explanation of C # Connections , which says:
You see that the C # compiler detects when a delegate forms a closure that is passed from the current scope, and it pushes the delegate and associated local variables into the generated compiler class. Thus, you just need a little compiler deception to pass an instance of the class generated by the compiler, so every time we call a delegate, we actually call a method in this class.
Thus, essentially a private variable is saved as a member variable of an anonymous class that also contains a delegate representing a lambda expression or other code that closes the variable.
If so, what happens when a method contains two different lambda expressions, and both of them refer to the same local variable?
void Test(IList list)
{
int i = 0;
list.Any( a => { Console.WriteLine("Lambda one says: {0}", i++); return true;} )
.Any( a => { Console.WriteLine("Lambda two says: {0}", i++); return true;} );
}
I am sure I know the behavior here. My question is: where exactly is it stored i?
source
share