VB.NET GoTo Example: Labels, Nested Loops

Use the GoTo keyword to go to a labeled statement. Break out of nested For-loops.

GoTo. In VB.NET we cannot go to a line number. Instead we provide a label. We then use GoTo "Label" to go to the labeled statement.Keywords

In a nested loop, it can be hard to exit outer loops. With a GoTo we can simply travel to a location after all enclosing loops. This is simpler and clearer.

First example. This statement transfers control to a Label in the current program. Here we specify a label named "World" and then Goto World. We Return when "i" reaches 3.If Then

Tip: With GoTo we can build loops without the For construct. This often become confusing. But GoTo has some uses.

VB.NET program that uses GoTo keyword Module Module1 Sub Main() Dim i As Integer = 0 Console.WriteLine("Hello") World: ' These statements come after World label. ' ... Print done when "i" is greater or equal to 3. If (i >= 3) Then Console.WriteLine("Done") Return End If ' ... Print string. Console.WriteLine("World") ' ... Increment and GoTo World label. i += 1 GoTo World End Sub End Module Output Hello World World World Done

Nested loops. Here we have two loops—the first iterates with the variable "i," and the second is nested within that loop. When the two loop indexes are certain values, we use a GoTo.For Each, For

And: With the GoTo we exit all enclosing loops. A "Finished" message is printed.

Tip: In this example the GoTo is similar to a "Return." For clearer code, we could refactor into a Function and use Return.

VB.NET program that uses GoTo, nested loops Module Module1 Sub Main() ' Two nested loops. ' ... On a certain condition, exit both loops with a GoTo. For i As Integer = 0 To 5 For x As Integer = 0 To 5 ' Display our indexes. Console.WriteLine("{0}, {1}", i, x) If x = 1 And i = 3 Then ' Use GoTo to exit two loops. GoTo AFTER End If Next Next AFTER: ' Print a message. Console.WriteLine("Finished") End Sub End Module Output 0, 0 0, 1 0, 2 0, 3 0, 4 0, 5 1, 0 1, 1 1, 2 1, 3 1, 4 1, 5 2, 0 2, 1 2, 2 2, 3 2, 4 2, 5 3, 0 3, 1 Finished

Some notes. Labels can be uppercase or lowercase. It is best to use a consistent naming scheme for labels. This depends on the programming style in your current project.

For complex code, GoTo can help simplify logic. In VB.NET we use this statement to move to a block that is within a containing scope. This is powerful and useful.
Dot Net Perls
© 2007-2020 Sam Allen. Every person is special and unique. Send bug reports to