This is not the first time I have seen a similar example of code on the network:

delegate void Function() ; public static void Main(string[] args) { List<Function> functions = new List<Function>() ; for(int i=0;i<10;i++){ functions.Add(delegate{ Console.WriteLine(i); }) ; } functions[0](); } 

A new method is added to the list of methods, which displays the value of the local variable i in the console. Its scope is a for loop. Behind him according to all the rules of the language that I know, it ceases to exist. In theory, its value should be passed to the function being created. But judging by the behavior, i remains a reference to the original definition in the loop. As a result, the result of executing the code is 10. Who can explain this behavior or at least give a link to the manuals, where is this explained?

0