I can't understand quite clearly the difference between two blocks of code. Consider there is a program
class Program
{
static void Main(string[] args)
{
List<Number> numbers = new List<Number>
{
new Number(1),
new Number(2),
new Number(3)
};
List<Action> actions = new List<Action>();
foreach (Number numb in numbers)
{
actions.Add(() => WriteNumber(numb));
}
Number number = null;
IEnumerator<Number> enumerator = numbers.GetEnumerator();
while (enumerator.MoveNext())
{
number = enumerator.Current;
actions.Add(() => WriteNumber(number));
}
foreach (Action action in actions)
{
action();
}
Console.ReadKey();
}
public static void WriteNumber(Number num)
{
Console.WriteLine(num.Value);
}
public class Number
{
public int Value;
public Number(int i)
{
this.Value = i;
}
}
}
The output is
1
2
3
3
3
3
These two blocks of code should work identically. But you can see that the closure is not working for the first loop. What am i missing?
Thanks in advance.