#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")

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")

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

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

One Response to #156 – Using break and continue in foreach Loops

  1. Moname says:

    Not the answer you re looking for? Browse other questions tagged c# loops enumeration or ask your own question .

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 )

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: