#1,126 – Rewriting a Loop to Avoid continue Statement

The continue statement allows jumping to end of the body of a loop, skipping the rest of the code within the loop.  Either the next iteration of the loop executes, or the code following the loop statement executes.

            List<Dog> myDogs = new List<Dog>
                new Dog {Name = "Kirby", Age = 5},
                new Dog {Name = "Jack", Age = 17},
                new Dog {Name = "Ruby", Age = 2}

            foreach (Dog d in myDogs)
                if (d.Age > 15)

                Console.WriteLine("{0} doing a trick", d.Name);

In most cases, you can rewrite the body of a loop and avoid using a continue statement by using an if statement.  The end result is generally more readable.

            foreach (Dog d in myDogs)
                if (d.Age <= 15)
                    Console.WriteLine("{0} doing a trick", d.Name);

#1,125 – Use of break and continue Statements

You can use the break statement to break out of a loop or switch statement, resuming execution at the endpoint of the enclosing statement.

You can use break within a switch statement or within while, do, for or foreach loops.

You can use the continue statement to jump unconditionally to the endpoint of the body of statements enclosed within a loop.  This will either cause execution to continue with the next iteration of the loop or will continue execution after the loop if the final iteration was being executed.

You can use continue within a while, do, for or foreach loop.

#1,124 – Iterate through Jagged Array with Nested foreach

You can’t use the foreach statement to directly iterate over all elements in a jagged array.  You can, however, iterate through the jagged array using nested foreach statements.  Each foreach statement independently iterates over one dimension of the jagged array.

            // Jagged array - 3 elements, each of which is array of int
            int[][] nums = new int[3][];

            nums[0] = new int[4];
            nums[2] = new int[3];

            for (int i = 0; i < 4; i++)
                nums[0][i] = i + 1;

            for (int i = 0; i < 3; i++)
                nums[2][i] = i + 101;

            // Iterate using foreach
            foreach (int[] intArray in nums)
                if (intArray != null)
                    Console.WriteLine("Array with {0} elements", intArray.Length);
                    foreach (int n in intArray)
                        Console.WriteLine("  {0}", n);
                    Console.WriteLine("Found null array");


#1,123 – Using foreach to Iterate on a Multidimensional Array

You can use the foreach statement to iterate through all elements in a multidimensional array.  The elements are iterated in a row-major order.  That is, all elements in the first row are enumerated, followed by the second row, etc.

            // 2-dimensional array
            string[,] twoByThree = new string[2, 3];

            // Populate with standard for loop
            for (int row = 0; row < 2; row++)
                for (int col = 0; col < 3; col++)
                    twoByThree[row, col] = string.Format("{0}/{1}", row + 1, col + 1);

            // Iterate using foreach
            foreach (string s in twoByThree)


#1,122 – It’s Okay to Capture Variables within a foreach Loop

Within a foreach loop, you capture an iteration variable when you save it for later use.  In versions of C# earlier than 5.0, this led to problems and unexpected behavior.  What ended up being captured was multiple copies of the last value of the iteration variable.

This has been changed in C# 5.0 so that you can capture an iteration variable within a foreach loop and get the expected behavior.

            string[] beatles = {"George", "John", "Paul", "Ringo"};

            List<Action> actionList = new List<Action>();
            List<string> guyList = new List<string>();

            foreach (string guy in beatles)
                actionList.Add(() => Console.WriteLine(guy));

            foreach (string guyInList in guyList)


            foreach (Action a in actionList)


#1,121 – Modifying Elements in a Collection Using foreach

Although the iteration variable in a foreach loop is read-only, you can still use the iteration variable to modify the elements of a collection, as long as they are reference-typed.  (Value-typed elements are immutable).  You’re not changing the iteration variable, but rather changing the object that it refers to.

            List<Dog> myDogs = new List<Dog>
                    new Dog {Name = "Kirby", Age = 15},
                    new Dog {Name = "Ruby", Age = 2},
                    new Dog {Name = "Jack", Age = 17}

            foreach (Dog d in myDogs)
                Console.Write(string.Format("{0} / ", d));


#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++)
                if (dogs[i].StartsWith("J"))
                    i++;  // skip next

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