Export (0) Print
Expand All

while

The while statement executes a statement or a block of statements until a specified expression evaluates to false. It takes the following form:

while (expression) statement

where:

expression
An expression that can be implicitly converted to bool or a type that contains overloading of the true and false operators. The expression is used to test the loop-termination criteria.
statement
The embedded statement(s) to be executed.

Remarks

Because the test of expression takes place before each execution of the loop, a while loop executes zero or more times.

A while loop can be terminated when a break, goto, return, or throw statement transfers control outside the loop. To pass control to the next iteration without exiting the loop, use the continue statement.

Example

// statements_while.cs
using System;
class WhileTest 
{
   public static void Main() 
   {
      int n = 1;

      while (n < 6) 
      {
         Console.WriteLine("Current value of n is {0}", n);
         n++;
      }
   }
}

Output

Current value of n is 1
Current value of n is 2
Current value of n is 3
Current value of n is 4
Current value of n is 5

See Also

C# Keywords | Compare to C++ | Iteration Statements | C. Grammar

Show:
© 2014 Microsoft