Home
C#
continue Keyword
This page was last reviewed on Jun 21, 2023.
Dot Net Perls
Continue. This C# statement alters control flow. It is used in loop bodies. It allows you to skip the execution of the rest of the iteration.
With the continue statement, we jump immediately to the next iteration in the loop. This keyword is often useful in while-loops, but can be used in any loop.
This program uses the continue statement. In a while-true loop, the loop continues infinitely. We call Sleep() to make the program easier to watch as it executes.
while
Thread.Sleep
Part 1 We increment the number "value" which starts at 0, and is incremented on its first iteration (so 0 is never printed).
Part 2 If the number is equal to 3, the rest of the iteration is terminated. Control moves to the next iteration.
using System; using System.Threading; class Program { static void Main() { int value = 0; while (true) { // Part 1: increment number. value++; // Part 2: if number is 3, skip the rest of this loop iteration. if (value == 3) { continue; } Console.WriteLine(value); // Pause. Thread.Sleep(100); } } }
1 2 4 5...
No enclosing loop. We must use a continue statement within a loop. We get an error from the compiler if no enclosing loop is found. The same restriction applies to break.
break
class Program { static void Main() { continue; } }
Error CS0139 No enclosing loop out of which to break or continue
Some notes. The C# language is a high-level language. When it is compiled, it is flattened into a sequence of instructions. These are intermediate language opcodes.
Intermediate Language
And When we specify a continue in a loop, branch statements (which jump to other instructions) are generated.
Some notes, branches. In branch statements, a condition is tested. And based on whether the condition is true, the runtime jumps to another instruction in the sequence.
Detail This new location is indicated by an offset in the opcode. So all branches "jump" to other parts of an instruction stream.
Note The continue statement could be implemented by branching to the top of the loop construct if the result of the expression is true.
true, false
A summary. The continue statement exits a single iteration of a loop. It does not terminate the enclosing loop entirely or leave the enclosing function body.
Continue uses. Continue is often most useful in while or do-while loops. For-loops, with well-defined exit conditions, may not benefit as much.
do while
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Jun 21, 2023 (edit).
Home
Changes
© 2007-2024 Sam Allen.