This tutorial explains how to exit a for loop in VB.NET.
For loops are an important part of any programming language, not just Visual Basic (.NET). Knowing how to use the For loop properly through the use of loop control statements is essential.
In this article we’re going to cover the Exit control statement, used to exit a For Loop prematurely (before it’s supposed to). The Exit statement is usually used in situations where an unexpected outcome has arisen, or the purpose of the For loop has been fulfilled.
Exit a For-Loop in VB.NET
Here is the syntax for the Exit statement. It works not only on For-Loops, but also on other loops such as “While” and “Do”. It can also be used to exit from Functions or Procedures prematurely (without returning).
Exit { Do | For | Function | Property | Select | Sub | Try | While }
If you want to use Exit on a “While Loop”, you will do “Exit While”. Similarly, if you want to do it on For Loop, you will do “Exit For”.
When you use the Exit statement, the loop/function will immediately end itself, and the execution will stop there. No further line will be executed.
Let’s take a look at a small example. In the below code, we will iterate from numbers 0 to 10 and print them out. We have an if-statement inside which will trigger an “Exit” if we encounter a number greater than 5.
For index As Integer = 0 To 10
If index > 5 Then
Exit For
End If
Console.Write(index.ToString & " ")
index += 1
Next
Console.WriteLine("")
The output:
0
1
2
3
4
5
A more realistic example would be something like where we are dividing numbers, and if the divisor is “0” we do not wish to continue, and simply exit from the program.
Here is another example, just for reference where we do the same thing with a While Loop.
Dim index As Integer = 0
Do While (index <= 10)
If index > 5 Then
Exit For
End If
Console.Write(index.ToString & " ")
index += 1
Loop
Console.WriteLine("")
Note: Keep in mind that an Exit statement does not work for nested loops (this applies to all types of loops). If you have two nested loops, and you call Exit within the nested loop, it will only break out the inner loop, not the outer one.
This marks the end of the “Exit a For Loop in VB.NET” article. Any suggestions or contributions for CodersLegacy are more than welcome. Questions regarding the article content can be asked in the comments section below.