I was attending the TechDays 2013 in the Netherlands this week and I got an interesting quiz question presented. The question was: What is the output of the following progra
In your case, the delegated methods are anonymous methods accessing a local variable (the for loop index i
). That is, these are clousures.
Since the anonymous method is called ten times after the for loop, it gets the most recent value for i.
Here's a simplified version of clousure behavior:
int a = 1;
Action a1 = () => Console.WriteLine(a);
Action a2 = () => Console.WriteLine(a);
Action a3 = () => Console.WriteLine(a);
a = 2;
// This will print 3 times the latest assigned value of `a` (2) variable instead
// of just 1.
a1();
a2();
a3();
Check this other Q&A (What are clousures in .NET?) on StackOverflow for more info about what are C#/.NET clousures!