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.

1
  • 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? Commented Apr 17, 2013 at 13:08

3 Answers 3

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
4
  • 3
    For completeness: Do While Not … can be written as Do Until. Commented Apr 17, 2013 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
    Commented Apr 17, 2013 at 13:05
  • Great, that's the explanation I was after.
    – jaffa
    Commented Apr 17, 2013 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
    Commented Aug 8, 2016 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.

-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.

5
  • 1
    I'm not asking about the difference between do { } while and while { } end while. I'm talking about the do while { }.
    – jaffa
    Commented Apr 17, 2013 at 11:03
  • There is no such thing as a do while{} in C# AFAIK
    – Borniet
    Commented Apr 17, 2013 at 11:24
  • No it isn't, the DO WHILE is in the same line and the block is underneath.
    – jaffa
    Commented Apr 17, 2013 at 12:38
  • Yes, but the logic is the same.
    – Borniet
    Commented Apr 17, 2013 at 12:39
  • 1
    Is this a VB question or a C# question.
    – dbasnett
    Commented Apr 17, 2013 at 13:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.