The Do...Loop cycle allows for the repetition of a code block with more flexible exit conditions than For (which is counter-oriented) or While (where the condition is always checked at the entry). In Visual Basic, there are four main variants of syntax:
' Entry check Do While condition ' Loop body Loop ' Exit check Do ' Loop body Loop While condition ' Similarly with Until: Do Until condition ' Loop body Loop Do ' Loop body Loop Until condition
You should use Do...Loop if:
Question: What happens if within the Do While condition loop the condition condition is initially false? Will any loop body be executed?
Answer: No, the loop body will not be executed at all, since the check occurs BEFORE the first execution.
Example:
Dim i As Integer = 10 Do While i < 5 Console.WriteLine(i) i += 1 Loop ' No lines will be printed.
Story
During the data parsing stage, a developer used a
Do Until reader.EndOfStreamloop inside which a line was read from the file. However, sinceEndOfStreamonly becomes true after an attempt to read beyond the file, the last line was not processed. The correct way is to useDo While Not reader.EndOfStreamor handle the reading line by line and end the loop based on the EOF condition.
Story
When migrating code from For to Do...Loop, a loop was implemented without explicit incrementation of the counter variable within the body. As a result, the program entered an infinite loop since the exit condition never occurred. It is necessary to always monitor key variable changes within the body of Do...Loop.
Story
In one of the reporting subsystems, a programmer used nested
Do...Loopcycles without considering the nesting ofExit Doconditions: the innerExit Doonly exited from the inner loop, not both. A short-term blocking bug was only detected in production with large volumes of data.