The For
Each
loop statement loops based on the elements in an expression. The type of the value returned by the expression in the For
Each
statement must be a collection type (defined below) and an implicit conversion must exist from the element type of the collection to the type of the iteration variable.
A type C
is said to be a collection type if all of the following are true:
C
contains a public instance method with the signature GetEnumerator()
that returns a type E
.E
contains a public instance method with the signature MoveNext()
and the return type Boolean
.E
contains a public instance property named Current
that has a getter. The type of this property is said to be the element type of the collection type.Before the loop begins, the expression is evaluated, GetEnumerator
is called on the expression and the returned value stored in a temporary. Then at the beginning of each loop, MoveNext
is called on the temporary. If it returns False
, the loop terminates. If it returns True
, the Current
property is retrieved, coerced to the type of the iterator variable (regardless of whether the conversion is implicit or explicit) and assigned to the iterator variable. Then the loop block is executed. When the Next
statement is reached, execution returns to the top of the loop. If a variable is specified after the Next
keyword, it must be the same as the first variable after the For
Each
.
If the loop control variable is a property, the property must be read-write, otherwise there is an error. If the loop control variable is a read-only data member, the loop must take place in a constructor appropriate for the type of the data member (that is, shared or not shared), otherwise there is an error.
Note that the System.Array
type is a collection type, and since all array types derive from System.Array
, any array type expression is permitted in a For
Each
statement. For single-dimensional arrays, the For
Each
statement enumerates the array elements in increasing index order, starting with index 0
and ending with index Length - 1
. For multi-dimensional arrays, the indices of the rightmost dimension are increased first.
For
Each
VariableExpression In
Expression StatementTerminatorNext
[ VariableExpression ] StatementTerminator