Was this page helpful?
Your feedback about this content is important. Let us know what you think.
Additional feedback?
1500 characters remaining
Export (0) Print
Expand All
Important This document may not represent best practices for current development, links to downloads and other resources may no longer be valid. Current recommended version can be found here.

do (C# Reference)

The do statement executes a statement or a block of statements enclosed in {} repeatedly until a specified expression evaluates to false. In the following example the do-while loop statements execute as long as the variable y is less than 5.

// statements_do.cs
using System;
public class TestDoWhile 
{
    public static void Main () 
    {
        int x = 0;
        do 
        {
            Console.WriteLine(x);
            x++;
        } while (x < 5);
    }
}

 
0
1
2
3
4

Unlike the while statement, a do-while loop is executed once before the conditional expression is evaluated.

At any point within the do-while block, you can break out of the loop using the break statement. You can step directly to the while expression evaluation statement by using the continue statement; if the expression evaluates to true, execution continues at the first statement in the loop. If the expression evaluates to false, execution continues at the first statement after the do-while loop.

A do-while loop can also be exited by the goto, return, or throw statements.

For more information, see the following sections in the C# Language Specification:

  • 5.3.3.8 Do statements

  • 8.8.2 The do statement

Community Additions

ADD
Show:
© 2015 Microsoft