C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
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
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