Home
VB.NET
GoTo Example: Labels, Nested Loops
This page was last reviewed on Nov 25, 2022.
Dot Net Perls
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.
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
Tip With GoTo we can build loops without the For construct. This often become confusing. But GoTo has some uses.
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
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.
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.
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
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 is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
No updates found for this page.
Home
Changes
© 2007-2024 Sam Allen.