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?
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.
The continue keyword is used to end the current iteration in a for loop (or a while loop), and continues to the next iteration.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With