+ 2

Find out the logic for this code

using System; using System.Collections.Generic; public class Program { public static void Main(string[] args) { var actions = new List(); for (int i = 0; i < 4; i++) actions.Add( () => Console.WriteLine(i)); foreach (var action in actions) action(); } } Ans: 4 4 4 4

5th May 2019, 5:08 AM
$@G@®️
$@G@®️ - avatar
1 Answer
0
Classic example. https://blogs.msdn.microsoft.com/ericlippert/2009/11/12/closing-over-the-loop-variable-considered-harmful/ using System; using System.Collections.Generic; public class Program { public static void Main(string[] args) { var actions = new List(); for (int i = 0; i < 4; i++) { var j = i; actions.Add( ) => Console.WriteLine(j)); } foreach (var action in actions) action(); } } Ans: 0 1 2 3
5th May 2019, 12:58 PM
Sergiy