Quantcast
Channel: 2,000 Things You Should Know About C# » foreach
Viewing all articles
Browse latest Browse all 10

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

$
0
0

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


Filed under: Statements Tagged: C#, foreach, Statements

Viewing all articles
Browse latest Browse all 10

Trending Articles