#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);
}

Advertisements

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: