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.
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.
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.
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 ModuleHello World World World Done
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.
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 Module0, 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
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.