O'Reilly logo

Microsoft® Visual C#® 2008 Step by Step by John Sharp

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Writing do Statements

The while and for statements both test their Boolean expression at the start of the loop. This means that if the expression evaluates to false on the very first test, the body of the loop does not run, not even once. The do statement is different; its Boolean expression is evaluated after each iteration, so the body always executes at least once.

The syntax of the do statement is as follows (don't forget the final semicolon):

do
    statement
while (booleanExpression);

You must use a statement block if the body of the loop comprises more than one statement. Here's a version of the example that writes the values 0 through 9 to the console, this time constructed using a do statement:

int i = 0; do { Console.WriteLine(i); i++; } while ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required