Nested Loops in Visual Basic
Over the years, I've spent my share of time programming in Visual Basic. From VBA to VB6 to VB .NET to VB 2005, there's been a feature buried in there that might be useful, and I had just never noticed it. Perhaps it's one of those "in" things that everyone else but me knows (just like in high school--a trauma that I'll carry with me to the grave <g>), but maybe you don't know about this, either.
You know, of course, that Visual Basic supports a number of different loops: For, For Each, While, Do While/Until. In each case, you can break out of the loop prematurely using the Exit For, Exit Do, or Exit While statement. I always thought that you could only break out of the inner-most loop. Not so--as long as you have nested loops of different types, the logic in your application can break you out to any level, as deep as you like.
For example, the following demo procedure shows how you can nest different loop types, and can exit any loop to any level:
Private Sub LoopTest()
Dim dir As New DirectoryInfo("C:\")
Dim i As Integer = 0
Dim j As Integer = 0
For Each file As FileInfo In dir.GetFiles("*.*")
Do While i < 10
Console.WriteLine("{0} {1}", i, file.FullName)
While j < 100
j += 1
If j = 1 Then
Exit While
End If
If j = 2 Then
Exit Do
End If
If j = 3 Then
Exit For
End If
End While
Console.WriteLine("===After Do While loop")
i += 1
Loop
Console.WriteLine("===After While loop")
Next
Console.WriteLine("===After For loop")
End Sub
Try the code--you'll see that you can jump from the inner loop to any level of outer loop. This technique obviously has limited uses, but when you need it, it's nice to know you can use it. The alternative, of course, is to use a Goto statement to break out of an inner loop, and gosh, how we hate Goto statements!