#156 – Using break and continue in foreach Loops

When iterating through array elements using the foreach statement, you can use the break statement to break out of the loop–when break is encountered, control is transferred to the code immediately following the loop and no more array elements will be processed.

            foreach (Person p in folks)
            {
                Console.WriteLine("{0} {1}", p.FirstName, p.LastName);

                // If we find Elvis, stop the presses
                if (p.FirstName == "Elvis")
                    break;
            }

The continue statement, when encountered in a foreach loop, causes control to transfer back to the top of the loop and move on to the next element.

            foreach (Person p in folks)
            {
                // Don't print out info for any Adolfs; move to the next person
                if (p.FirstName == "Adolf")
                    continue;

                Console.WriteLine("{0} {1}", p.FirstName, p.LastName);
            }
Advertisements