HomeSearch

VB.NET Do Until Loops

Evaluate the Do Until loop construct. This loop continues running while the condition is False.

Do Until. All loops in VB.NET have a similar purpose. They cause a block of statements to repeat a certain number of times. The Do Until loop is similar to the Do While loop.

Notes, syntax. Do Until uses a slightly different syntax than Do While. In this loop, the Until condition causes termination when it evaluates to True.While, Do While

This program uses both a Do Until loop and a Do While loop. The Do Until loop has the condition "i = 10". This loop will continue repeating until the variable "i" is equal to ten.

Caution: This syntax can easily result in an infinite loop if you are not careful.

And: We find that Do Until has all the same problems as While and Do While in this respect.

VB.NET program that uses Do Until Module Module1 Sub Main() Dim i As Integer = 0 ' Example Do Until loop. Do Until i = 10 Console.WriteLine("Do Until: {0}", i) i += 1 Loop Console.WriteLine() i = 0 ' Equivalent Do While loop. Do While i < 10 Console.WriteLine("Do While: {0}", i) i += 1 Loop End Sub End Module Output Do Until: 0 Do Until: 1 Do Until: 2 Do Until: 3 Do Until: 4 Do Until: 5 Do Until: 6 Do Until: 7 Do Until: 8 Do Until: 9 Do While: 0 Do While: 1 Do While: 2 Do While: 3 Do While: 4 Do While: 5 Do While: 6 Do While: 7 Do While: 8 Do While: 9

Syntax. This syntax may be more readable if the terminating condition for the loop is the most intuitive. It really just depends on what you prefer.

Note: The Do While syntax is more expected for developers used to C# or C-like languages.

Conceptually: The Do Until syntax could be thought of as a "Do While Not" syntax. It changes a Do While loop to evaluate while False.

Iteration. Iteration variables in the Do Until loop must be incremented with a separate statement. If you have an iteration variable (such as i) it is probably better to use a For-loop.

And: If you looping over elements of a collection, it is probably best to use a For-Each loop.

For Each, For

A review. Do Until may provide a clearer syntax for loops in some programs. For developers of languages based on C, though, the syntax may be less intuitive and worth avoiding.

Final notes. Do Until loop provides no advantages other than its inversion of the loop condition. It continues looping while False and stops when True.
Home
Dot Net Perls
© 2007-2020 Sam Allen. Every person is special and unique. Send bug reports to info@dotnetperls.com.