Data Types. The data type of element must be such that the data type of the elements of group can be converted to it.
The data type of group must be a reference type that refers to a collection or an array. This means that group must refer to an object that implements the IEnumerable interface of the System.Collections namespace or the IEnumerable<(Of <(T>)>) interface of the System.Collections.Generic namespace. IEnumerable defines the GetEnumerator method, which returns an enumerator object for the collection. The enumerator object implements the IEnumerator interface of the System.Collections namespace and exposes the Current property and the Reset and MoveNext methods. Visual Basic uses these to traverse the collection.
The elements of group are usually of type Object but can have any run-time data type.
Narrowing Conversions. When Option Strict is set to On, narrowing conversions ordinarily cause compiler errors. In the following example, the assignment of m as the initial value for n does not compile with Option Strict on because the conversion of a Long to an Integer is a narrowing conversion.
Dim m As Long = 987
' Does not compile.
'Dim n As Integer = m
However, conversions from the elements in group to element are evaluated and performed at run time, and the narrowing conversion error is suppressed. In the following example, no compiler error is reported in the For Each loop, even though it requires the same conversion from Long to Integer that caused an error in the previous example.
Option Strict On
Module Module1
Sub Main()
' The assignment of m to n causes a compiler error when
' Option Strict is on.
Dim m As Long = 987
'Dim n As Integer = m
' The For Each loop requires the same conversion, but
' causes no errors. The output is 45 3 987.
For Each p As Integer In New Long() {45, 3, 987}
Console.Write(p & " ")
Next
Console.WriteLine()
End Sub
End Module
The lack of a compiler error does not eliminate the risk of a run-time error. In the following example, no compiler error is reported, but a run-time error occurs when ToInteger is applied to 9876543210. The run-time error occurs whether Option Strict is on or off.
Option Strict On
Module Module1
Sub Main()
' The assignment of m to n causes a compiler error when
' Option Strict is on.
Dim m As Long = 9876543210
'Dim n As Integer = m
Try
' The For Each loop requires the same conversion, but
' is not flagged by the compiler. A run-time error is
' raised because 9876543210 is too large for type Integer.
For Each p As Integer In New Long() {45, 3, 9876543210}
Console.Write(p & " ")
Next
Console.WriteLine()
Catch e As System.OverflowException
Console.WriteLine()
Console.WriteLine(e.Message)
End Try
End Sub
End Module
Declaration. If element has not been declared outside this loop, you must declare it within the For Each statement. You can declare the type of element explicitly by using an As statement, or you can rely on type inference to assign the type. In either case, the scope of element is the body of the loop. However, you cannot declare element both outside and inside the loop.
Number of Iterations. Visual Basic evaluates the collection only once, before the loop begins. If your statement block changes element or group, these changes do not affect the iteration of the loop.
Nesting Loops. You can nest For Each loops by placing one loop within another. However, each loop must have a unique element variable.
You can also nest different kinds of control structures within one another. For more information, see Nested Control Structures.
Note: |
|---|
If a
Next statement of an outer nesting level is encountered before the Next of an inner level, the compiler signals an error. However, the compiler can detect this overlapping error only if you specify element in every Next statement.
|
Identifying the Control Variable. You can optionally specify element in the Next statement. This improves the readability of your program, especially if you have nested For Each loops. You must specify the same variable as the one that appears in the corresponding For Each statement.
Transferring Out of the Loop. The Exit Statement (Visual Basic) transfers control immediately to the statement following the Next statement. You might want to exit a loop if you detect a condition that makes it unnecessary or impossible to continue iterating, such as an erroneous value or a termination request. Also, if you catch an exception in a Try...Catch...Finally statement, you can use Exit For at the end of the Finally block.
You can place any number of Exit For statements anywhere in the For Each loop. Exit For is often used after evaluating some condition, for example in an If...Then...Else structure.
Endless Loops. One use of Exit For is to test for a condition that could cause an endless loop, which is a loop that could run an extremely large or even infinite number of times. If you detect such a condition, you can use Exit For to escape the loop. For more information, see Do...Loop Statement (Visual Basic).