This works fine (means as expected) in C# 5.0:
var actions = new List<Action>();
foreach (var i in Enumerable.Range(0, 10))
{
actions.Add(() => Console.WriteLine(i));
}
foreach (var act in actions) act();
Prints 0 to 9. But this one shows 10 for 10 times:
var actions = new List<Action>();
for (var i = 0; i < 10; i++)
{
actions.Add(() => Console.WriteLine(i));
}
foreach (var act in actions) act();
Question: This was a problem that we had in C# versions before 5.0; so we had to use a loop-local placeholder for the closure and it's fixed now - in C# 5.0 - in "foreach" loops. But not in "for" loops!
What is the reasoning behind this (not fixing the problem for for loops too)?
forloops as well"?var idepending on the scope of the lambdas IIRCpublic IEnumerable<Person> FindAdults(int minimumAge) { return people.Where(p => p.Age >= minimumAge); }By the time that predicate is executed, the parameter won't be in scope any more. Without that ability to capture variables, LINQ would be massively weaker.