C#: Break vs. Continue in Foreach Loops

A C# Quick Tip: You’ve probably seen ‘break’ before in Switch Case statements, but it also plays an important role in Foreach Loops.

To break completely out of a foreach loop (foregoing all the remaining loops), use: break;

To go to the next iteration in the loop, use: continue;

When is ‘break’ useful? It is particularly useful if you’re looping through an a collection of Objects (like Rows in a Datatable) and you’re searching for a particular match. When you find that match, there’s no need to continue through the remaining rows, so you want to Break out. There are plenty of other cases as well.

‘Continue’ is useful when you’ve accomplished what you need to in side a loop iteration and you don’t want to process the remaining code for that particular iteration. You’ll normally have ‘continue’ after an ‘if’.

,

One Response to C#: Break vs. Continue in Foreach Loops

  1. Anthony May 23, 2011 at 10:06 am #

    Perfect simple summary. Thanks! 🙂

Powered by WordPress. Designed by Woo Themes