Export (0) Print
Expand All

do

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

do statement while (expression);

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

Unlike the while statement, the body loop of the do statement is executed at least once regardless of the value of the expression.

Example

// statements_do.cs
using System;
public class TestDoWhile 
{
   public static void Main () 
   {
      int x;
      int y = 0;

      do 
      {
         x = y++;
         Console.WriteLine(x);
      }

      while(y < 5);
   }   
}

Output

0
1
2
3
4

Example

Notice in this example that although the condition evaluates to false, the loop will be executed once.

// statements_do2.cs
using System;
class DoTest {
   public static void Main() 
   {
      int n = 10;
      do 
      {
         Console.WriteLine("Current value of n is {0}", n);
         n++;
      } while (n < 6);
   }
}

Output

Current value of n is 10

See Also

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

Show:
© 2014 Microsoft