Visual Basic .NET - Goto Statement

In VB.NET, the GoTo statement is used to transfer the control of the program to a specific line label. The GoTo statement is generally used to handle certain conditions or situations that require immediate transfer of control to a different part of the code.

GoTo label

Here, label is the line label to which the control is transferred.

Dim num As Integer = 10
If num > 0 Then
   GoTo Positive
ElseIf num = 0 Then
   GoTo Zero
Else
   GoTo Negative
End If
Positive:
Console.WriteLine("Number is positive.")
GoTo ExitHere
Zero:
Console.WriteLine("Number is zero.")
GoTo ExitHere
Negative:
Console.WriteLine("Number is negative.")
GoTo ExitHere
ExitHere:
Console.WriteLine("Exiting the program.")

In the above example, the GoTo statement is used to jump to a specific label based on the value of the num variable. If num is greater than 0, the control jumps to the Positive label, if num is equal to 0, the control jumps to the Zero label, and if num is less than 0, the control jumps to the Negative label. After each label statement, the control is transferred to the ExitHere label, which indicates the end of the program.

The GoTo statement can also be used to implement error handling in VB.NET. For example, if an error occurs in a specific section of the code, the control can be transferred to an error handling section using the GoTo statement.

However, the use of GoTo statement is generally discouraged in modern programming practices, as it can make the code harder to read and maintain. In most cases, other control structures such as If-Then-Else, Select-Case or Try-Catch-Finally blocks can be used instead of the GoTo statement.