Possible Duplicate:
Is there a reason for C#'s reuse of the variable in a foreach?
Looping through a list of Actions
today I encounter a problem about the C# foreach function, it didn't give me the proper result as I expected. here is the code:
using System;
using System.Collections.Generic;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
int[] data = new int[] { 1, 2, 3, 4, 5 };
List<Func<int>> actions = new List<Func<int>>();
foreach (int x in data)
{
actions.Add(delegate() { return x; });
}
foreach (var foo in actions)
{
Console.WriteLine(foo());
}
Console.ReadKey();
}
}
}
when I Run it in console application and it has five 5 printed on the screen. Why? I just cann't understand. Have asked some people and they just said that there is closure in this code, But I am not very clear about this, I remember that in javascript , I often encounter the closure, but in above code, why there is closure? thx.