#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

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 comment