+ 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
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