C# break and continue statements



Using the break statement

The break statement, when executed in a while, for, do…while, switch, or foreach, causes immediate exit from that statement.

Common uses of the break statement are to escape early from a repetition statement or to skip the remainder of a switch.

The following code example shows how to use a break statement:

    // break statement exiting a for statement.
    using System;   
    public class BreakTest
    {
       public static void Main( string[] args )
       {
          int count; // control variable also used after loop terminates
    
          for ( count = 1; count <= 10; ++count ) // loop 10 times
          {
             if ( count == 5 ) // if count is 5, 
                break; // terminate loop   
             Console.Write( "{0} ", count );
          } // end for   
          Console.WriteLine( "\nBroke out of loop at count = {0}", count );
          Console.ReadLine();
       } // end Main
    } // end class BreakTest

    Program output:
    1 2 3 4
    Broke out of loop at count = 5

Using the continue statement

The continue statement, when executed in a while, for, do…while, switch, or foreach, skips the remaining statements in the loop body and proceeds with the next iteration of the loop.

In while and do…while statements, the app evaluates the loop-continuation test immediately after the continue statement executes. In a for statement, the increment expression normally executes next, then the app evaluates the loop-continuation test.

The following code example shows how to use a continue statement:

    // continue statement terminating an iteration of a for statement.
    using System;
    public class ContinueTest
    {
       public static void Main( string[] args )
       {
          for ( int count = 1; count <= 10; ++count ) // loop 10 times
          {
             if ( count == 5 ) // if count is 5, 
                continue; // skip remaining code in loop    
             Console.Write( "{0} ", count );
          } // end for    
          Console.WriteLine( "\nUsed continue to skip displaying 5" );
          Console.ReadLine();
       } // end Main
    } // end class ContinueTest

    Output:
    1 2 3 4 6 7 8 9 10
    Used continue to skip displaying 5

Ads Right