Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use the 'continue' keyword in C#

Tags:

c#

.net

continue

Recently, I was going through an open-source project and although I have been developing for several years in .NET, I hadn't stumbled across the continue keyword before.

Question: What are some best practices or areas that would benefit from using the continue keyword? Is there a reason I might not have seen it previously?

like image 652
Rion Williams Avatar asked Nov 01 '11 21:11

Rion Williams


People also ask

When continue is used in C?

The continue statement passes control to the next iteration of the nearest enclosing do , for , or while statement in which it appears, bypassing any remaining statements in the do , for , or while statement body.

What is the use of continue keywords?

The continue keyword is used to end the current iteration in a for loop (or a while loop), and continues to the next iteration.

When to Use continue or break?

Key Differences Between Break and Continue A break is used to abruptly terminate the execution of the upcoming statements and iterations of a loop and move to the next statement after the loop, whereas continue is used for a different purpose, i.e. to skip the current iteration and move to the next iteration.

What is the use of continue statement with example?

In computer programming, the continue statement is used to skip the current iteration of the loop and the control of the program goes to the next iteration.


2 Answers

You use it to immediately exit the current loop iteration and begin the next, if applicable.

foreach (var obj in list) {     continue;      var temp = ...; // this code will never execute } 

A continue is normally tied to a condition, and the condition could usually be used in place of the continue;

foreach (var obj in list) {      if (condition)        continue;      // code }  

Could just be written as

foreach (var obj in list) {     if (!condition)     {         // code     } } 

continue becomes more attractive if you might have several levels of nested if logic inside the loop. A continue instead of nesting might make the code more readable. Of course, refactoring the loop and the conditionals into appropriate methods would also make the loop more readable.

like image 196
Anthony Pegram Avatar answered Oct 23 '22 19:10

Anthony Pegram


The continue keyword is used to skip the rest of the loop block and continue on. For example:

for(int i = 0; i < 5; i++) {    if(i == 3) continue; //Skip the rest of the block and continue the loop     Console.WriteLine(i); } 

Will print:

0 1 2 4 
like image 40
Mike Christensen Avatar answered Oct 23 '22 18:10

Mike Christensen