RSS

break vs. continue in C# .NET

03 Feb

The Break Statement

The break statement enables you to exit the loop entirely, and skip to the next line of code outside the loop. The break statement is particularly useful if you are iterating through an array looking for a record, and you want to exit the loop when you have found the record.

The following code example shows how to exit a while loop if the value 5 is found in an array.

int[] oldNumbers = { 1, 2, 3, 4, 5, 6, 7, 8 };

int count = 0;

while (oldNumbers.Length > count)

{

if (oldNumbers[count] == 5)

{

break;

}

count++;

}

The Continue Statement

The continue statement is similar to the break statement except that, instead of exiting the loop entirely, you skip the remaining code in the current iteration, test the condition, and then start the next iteration of the loop. The following code example shows how to add additional logic to a while loop that will not execute when the value 5 is found.

 int[] oldNumbers = { 1, 2, 3, 4, 5, 6, 7, 8 };

int count = 0;

while (oldNumbers.Length > count)

{

if (oldNumbers[count] == 5)

{

continue;

}

// Code that won’t be hit when the value 5 is found

count++;

}

The continue statement produces identical behavior when it is used with the while and do loops. The only subtle difference is that, when it is used with the for loop, the remaining code in the current iteration is skipped as with the other loops, but the modifier in the for specification is incremented before the condition is tested, and the next iteration begins.

 
Leave a comment

Posted by on February 3, 2012 in Visual C# . NET

 

Tags: , , , , , ,

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 )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: