This documentation is archived and is not being maintained.

10.9.1 While...End While and Do...Loop Statements

Visual Studio .NET 2003

A While or Do loop statement loops based on a Boolean expression. A While loop statement loops as long as the Boolean expression evaluates to True; a Do loop statement may contain a more complex condition. In either case, the expressions must be classified as values and must be implicitly convertible to Boolean.

An expression may be placed after the Do keyword or after the Loop keyword, but not after both. It is also valid to specify no expression at all; in that case, the loop will never exit. If the expression is placed after Do, it will be evaluated before the loop block is executed on each iteration. If the expression is placed after Loop, it will be evaluated after the loop block has executed on each iteration. Placing the expression after Loop will therefore generate one more loop than placement after Do. The following example demonstrates this behavior:

Module Test
    Sub Main()
        Dim x As Integer

        x = 3
        Do While x = 1
            Console.WriteLine("First loop")

            Console.WriteLine("Second loop")
        Loop While x = 1
    End Sub
End Module

The code produces the output:

Second Loop
Third Loop
Third Loop

In the case of the first loop, the condition is evaluated before the loop executes. In the case of the second loop, the condition is executed after the loop executes. The conditional expression must be prefixed with either a While keyword or an Until keyword. The former breaks the loop if the condition evaluates to False, the latter when the condition evaluates to True.

WhileStatement ::=
   While Expression StatementTerminator
   [ Block ]
   End While StatementTerminator
DoLoopStatement ::=
   Do [ WhileOrUntil Expression ] StatementTerminator
   [ Block ]
   Loop [ WhileOrUntil Expression ] StatementTerminator
WhileOrUntil ::= While | Until

See Also

10.9.2 For...Next Statements | 10.9.3 For Each...Next Statements | 10.9 Loop Statements | While...End While Statements (Visual Basic Language Reference) | While Statements (Visual Basic Language Concepts) | Do...Loop Statements (Visual Basic Language Reference) | Do...Loop Statements (Visual Basic Language Concepts)