Please refer to question Captured variable in a loop in C#
I want to ask why does the variable behaves strange?
static void Main(string[] args)
{
int[] numbers = new int[] { 1, 2, 3 };
List<Action> lst_WANT = new List<Action>();
foreach (var currNum in numbers)
{
//--------- STRANGE PART -------------
int holder = currNum;
lst_WANT.Add(() =>
{
Console.WriteLine(holder);
});
}
foreach (var want in lst_WANT)
want();
Console.WriteLine("================================================");
List<Action> lst_DONT_WANT = new List<Action>();
foreach (var currNum in numbers)
{
lst_DONT_WANT.Add(() =>
{
Console.WriteLine(currNum);
});
}
foreach (var dont_want in lst_DONT_WANT)
dont_want();
Console.ReadKey();
}
The final output is:
1
2
3
--
3
3
3