Apparently, one can create a Do ... Loop
-Loop without a condition. The following code compiles with .NET 4.5 (fiddle) as well as with Roslyn (fiddle):
Public Sub Main()
Do
Console.WriteLine("Hello World")
Exit Do
Loop
End Sub
However, the grammar on the documentation page only offers the following two options:
Do { While | Until } condition
[ statements ]
[ Continue Do ]
[ statements ]
[ Exit Do ]
[ statements ]
Loop
-or-
Do
[ statements ]
[ Continue Do ]
[ statements ]
[ Exit Do ]
[ statements ]
Loop { While | Until } condition
Is this a bug in the compiler, a bug in the documentation or did I just not look hard enough?
Yes it is perfectly correct to do so.
A "Do While" loop statement runs while a logical expression is true. This means that as long as your expression stays true, your program will keep on running. Once the expression is false, your program stops running. A "Do Until" loop statement runs until a logical statement is true.
First, the statement is executed. Then, the condition is evaluated, and if it is true, the statement is executed again, continuing in this way until the condition becomes false. At this point the statement immediately following the do loop is executed.
When in doubt, consult the language specification, rather than the reference:
10.9.1 While...End While and Do...Loop Statements
A
While
orDo
loop statement loops based on a Boolean expression. ... An expression may be placed after theDo
keyword or after theLoop
keyword, but not after both. ... It is also valid to specify no expression at all;
(My emphasis)
The language reference tries to be more straightforward but may lose essential details. The language specification should match what the compiler implements.
I think the key sentence in the documentation is
You can use either While or Until to specify condition, but not both.
So if you want to specify a condition you have to use either. Without a condition you do not have to specify anything.
Leaving off the condition is perfectly valid and will result in an infinite loop.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With