#1,120 – The Iteration Variable in a foreach Loop Is Read-Only

Unlike the for loop, the iteration variable in a foreach loop is read-only.  Attempting to assign a value to the variable within the body of the loop will result in a compile-time error.

            string[] dogs = {"Kirby", "Jack", "Ruby", "Lassie"};

            // for loop allows writing to iteration variable
            Console.WriteLine("= for loop");
            for (int i = 0; i < dogs.Length; i++)
            {
                Console.WriteLine(dogs[i]);
                if (dogs[i].StartsWith("J"))
                    i++;  // skip next
            }

            Console.WriteLine("= foreach loop");
            foreach (string s in dogs)
            {
                if (s.StartsWith("J"))
                    s = "****";     // ERROR
                Console.WriteLine(s);
            }

1120-001

Advertisements

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

One Response to #1,120 – The Iteration Variable in a foreach Loop Is Read-Only

  1. Pingback: Dew Drop – June 19, 2014 (#1800) | Morning Dew

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: