21

What's the difference between Do While where the statement is the first line in the loop block and just the single While in VB.NET?

They don't seem to offer any difference in behavior.

essential
  • 648
  • 1
  • 7
  • 19
jaffa
  • 26,770
  • 50
  • 178
  • 289
  • 1
    There is no difference. One is there for legacy reasons. BASIC is an ooooooold language, and Vb.Net still carries some of that baggage e.g. `Mid(MyStr, 2) = "Hi"` want to guess what that does? – Binary Worrier Apr 17 '13 at 13:08

3 Answers3

32

In Visual Basic these are identical:

    Dim foo As Boolean = True

    While Not foo
        Debug.WriteLine("!")
    End While

    Do While Not foo
        Debug.WriteLine("*")
    Loop

These are not; the do executes once:

    Dim foo As Boolean = True

    While Not foo
        Debug.WriteLine("!")
    End While

    Do
        Debug.WriteLine("*")
    Loop While Not foo
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
dbasnett
  • 11,334
  • 2
  • 25
  • 33
  • 3
    For completeness: `Do While Not …` can be written as `Do Until`. – Konrad Rudolph Apr 17 '13 at 13:04
  • 2
    Honestly, I actively avoid `Do Until`. I've seen too may people accidentally throw infinite loops into production code with it. – valverij Apr 17 '13 at 13:05
  • Great, that's the explanation I was after. – jaffa Apr 17 '13 at 14:56
  • 1
    I have always used Do Until. Never had a problem with infinite loops. You just need to make sure you update the variable being tested during the loop. If people are putting infinite loops into production code, then they're not testing it properly. – tolsen64 Aug 08 '16 at 15:17
1

In DO...WHILE, the code inside the loop is executed at least once

In WHILE Loop, the code inside the loop is executed 0 or more times.

noblepal
  • 11
  • 1
-6

Do While executes first and then checks if valid. While checks first and then executes.

while (1!=1){ echo 1} 

will output nothing

But

do{echo 1} while (1!=1) 

will output 1 once.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Borniet
  • 3,544
  • 4
  • 24
  • 33