1

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

Cœur
  • 37,241
  • 25
  • 195
  • 267
GaryX
  • 737
  • 1
  • 5
  • 20

1 Answers1

3

All of your lambda expressions are sharing the same currNum variable.
After the loop finishes, that variable is 3.

By using a separate variable declared inside the loop, you're forcing each lambda expression to use its own variable that doesn't change.

Eric Lippert explains this.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964