0

Noob here, apologies if I'm not using terminology correctly...

Each code block below starts with a list of letters { "a", "c" } and creates an action delegate to later insert "b" prior to "c".

I find that when I use the "for variable", i, for the index parameter of List.Insert(), the value passed is not respected when I call the action delegate later on. But if I capture i in a new int and pass that when creating the action delegate, then the value is respected. Further, if I inspect the variables i and index on the iteration where the action delegate is created, they both hold the same value: 1.

I would expect that both code blocks would return "abc", but obviously they don't.

Why is the behavior is different between the two sets of code?

This code outputs "acb":

        public void Test()
        {
            List<string> letters = new List<string>() { "a", "c" };
            List<Action> actions = new List<Action>();
            for (int i = 0; i < letters.Count; i++)
            {
                string letter = letters[i];
                if (letter == "c")
                {
                    actions.Add(new Action(() => letters.Insert(i, "b")));
                }
            }

            for (int i = actions.Count - 1; i > -1; i--)
                actions[i]();

            foreach (var letter in letters)
                Debug.Write(letter);
        }

This code outputs "abc":

        public void Test()
        {
            List<string> letters = new List<string>() { "a", "c" };
            List<Action> actions = new List<Action>();
            for (int i = 0; i < letters.Count; i++)
            {
                string letter = letters[i];
                if (letter == "c")
                {
                    int index = i; // Using "index" instead of i when creating the action
                    actions.Add(new Action(() => letters.Insert(index, "b")));
                }
            }

            for (int i = actions.Count - 1; i > -1; i--)
                actions[i]();

            foreach (var letter in letters)
                Debug.Write(letter);
        }
Dan Push
  • 1
  • 1
  • 2

0 Answers0