#583 – You Can’t Modify the Iterator Variable Within a foreach Loop

The iterator variable within a foreach loop is the variable that takes on the value of each item within the corresponding collection, each time through the loop.

            string[] puppets =
                {"Crow T. Robot", "Howdy Doody", "Kermit",
                 "King Friday XIII", "Lamb Chop"};

            // nextPuppet is the iterator variable
            foreach (string nextPuppet in puppets)
            {
                Console.WriteLine("Puppet: {0}", nextPuppet);
            }

If you try to modify this iterator variable within the loop, however, you’ll get a compile-time error.

foreach (string nextPuppet in puppets)
{
    nextPuppet = "(" + nextPuppet + ")";
    Console.WriteLine("Puppet: {0}", nextPuppet);
}

Advertisement