When a variable is closed twice, where is it stored?

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?

+4
source share
1 answer

There is only one closure class for this method, not one for the anonymous method. This class will have two instance methods and a field. The field will save the value i, and both methods will match your two anonymous methods.

+3
source

Source: https://habr.com/ru/post/1669869/


All Articles