For Each...Next Statement (Visual Basic)

Repeats a group of statements for each element in a collection.

For Each element [ As datatype ] In group
    [ statements ]
    [ Exit For ]
    [ statements ]
Next [ element ]

Parts

  • element
    Required in the For Each statement. Optional in the Next statement. Variable. Used to iterate through the elements of the collection.

  • datatype
    Required if element is not already declared. Data type of element.

  • group
    Required. Object variable. Refers to the collection over which the statements are to be repeated.

  • statements
    Optional. One or more statements between For Each and Next that run on each item in group.

  • Exit For
    Optional. Transfers control out of the For Each loop.

  • Next
    Required. Terminates the definition of the For Each loop.

Remarks

Use a For Each...Next loop when you want to repeat a set of statements for each element of a collection or array.

A For...Next Statement (Visual Basic) works well when you can associate each iteration of a loop with a control variable and determine that variable's initial and final values. However, when you are dealing with a collection, the concept of initial and final values is not meaningful, and you do not necessarily know how many elements the collection has. In this case, a For Each...Next loop is a better choice.

Rules

  • 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<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).

Behavior

  • Entry into the Loop. When execution of the For Each...Next loop begins, Visual Basic verifies that group refers to a valid collection object. If not, it throws an exception. Otherwise, it calls the MoveNext method and the Current property of the enumerator object to return the first element. If MoveNext indicates that there is no next element, that is, if the collection is empty, then the For Each loop terminates and control passes to the statement following the Next statement. Otherwise, Visual Basic sets element to the first element and runs the statement block.

  • Iterations of the Loop. Each time Visual Basic encounters the Next statement, it returns to the For Each statement. Again it calls MoveNext and Current to return the next element, and again it either runs the block or terminates the loop depending on the result. This process continues until MoveNext indicates that there is no next element or an Exit For statement is encountered.

  • Termination of the Loop. When all the elements in the collection have been successively assigned to element, the For Each loop terminates and control passes to the statement following the Next statement.

  • Changing Iteration Values. Changing the value of element while inside a loop can make it more difficult to read and debug your code. Changing the value of group does not affect the collection or its elements, which were determined when the loop was first entered.

  • Traversal Order. When you execute a For Each...Next loop, traversal of the collection is under the control of the enumerator object returned by the GetEnumerator method. The order of traversal is not determined by Visual Basic, but rather by the MoveNext method of the enumerator object. This means that you might not be able to predict which element of the collection is the first to be returned in element, or which is the next to be returned after a given element.

    If your code depends on traversing a collection in a particular order, a For Each...Next loop is not the best choice unless you know the characteristics of the enumerator object the collection exposes. You might achieve more reliable results using a different loop structure, such as For...Next or Do...Loop.

  • Modifying the Collection. The enumerator object returned by GetEnumerator normally does not allow you to alter the collection by adding, deleting, replacing, or reordering any elements. If you alter the collection after you have initiated a For Each...Next loop, the enumerator object becomes invalid, and the next attempt to access an element results in an InvalidOperationException exception.

    However, this blocking of modification is not determined by Visual Basic, but rather by the implementation of the IEnumerable interface. It is possible to implement IEnumerable in such a way as to allow modification during iteration. If you are considering doing such dynamic modification, be sure you understand the characteristics of the IEnumerable implementation on the collection you are using.

  • Modifying Collection Elements. The Current property of the enumerator object is ReadOnly (Visual Basic), and it returns a local copy of each collection element. This means that you cannot modify the elements themselves in a For Each...Next loop. Any modification you make affects only the local copy from Current and is not reflected back into the underlying collection. However, if an element is a reference type, you can modify the members of the instance to which it points. The following example illustrates this.

    Sub lightBlueBackground(ByVal thisForm As System.Windows.Forms.Form)
        For Each thisControl As System.Windows.Forms.Control In thisForm.Controls
            thisControl.BackColor = System.Drawing.Color.LightBlue
        Next thisControl
    End Sub
    

    The preceding example can modify the BackColor member of each thisControl element, although it cannot modify thisControl itself.

  • Traversing Arrays. Because the Array class implements the IEnumerable interface, all arrays expose the GetEnumerator method. This means that you can iterate through an array with a For Each...Next loop. However, you can only read the array elements, not change them. For an illustration, see How to: Run Several Statements for Each Element in a Collection or Array.

Example

The following example uses the For Each...Next statement to search all elements in a collection for the string "Hello". The example assumes that the collection thisCollection has already been created and that its elements are of type String.

Dim found As Boolean = False 
Dim thisCollection As New Collection
For Each thisObject As String In thisCollection
    If thisObject = "Hello" Then
        found = True 
        Exit For 
    End If 
Next thisObject

See Also

Tasks

How to: Run Several Statements for Each Element in a Collection or Array

How to: Improve the Performance of a Loop

Concepts

Loop Structures

Collections in Visual Basic

Widening and Narrowing Conversions

Reference

While...End While Statement (Visual Basic)

Do...Loop Statement (Visual Basic)

Change History

Date

History

Reason

July 2008

Added section about narrowing conversions.

Customer feedback.