It is possible to force an early iteration of a loop, bypassing the loop’s normal control structure. This is accomplished using continue. The continue statement forces the next iteration of the loop to take place, skipping any code in between. Thus, continue is essentially the complement of break. For example, the following program uses continue to help print the even numbers between 0 and 100.
// Use continue. using System; class ContDemo { public static void Main() { // print even numbers between 0 and 100 for(int i = 0; i <= 100; i++) { if((i%2) != 0) continue; // iterate Console.WriteLine(i); } } }
Only even numbers are printed, because an odd number will cause the loop to iterate early, bypassing the call to WriteLine( ).
In while and do-while loops, a continue statement will cause control to go directly to the conditional expression and then continue the looping process. In the case of the for, the iteration expression of the loop is evaluated, the conditional expression is executed, and then the loop continues.
Good uses of continue are rare. One reason is that C# provides a rich set of loop statements that fit most applications. However, for those special circumstances in which early iteration is needed, the continue statement provides a structured way to accomplish it.
The return statement causes a method to return. It can also be used to return a value. It is examined in Chapter 6.