The For Each loop in Visual Basic is intended for sequentially iterating over all elements of a collection or array. Its use simplifies working with enumerable objects (Collection, Array, lists, etc.) without requiring explicit index access.
Syntax:
For Each element As DataType In collection ' Actions with element Next
Differences from other loops:
For — requires specifying a counter and a range, effective when index-based access to elements is needed.While — executes as long as the condition is true, suitable for unpredictable iteration counts.For Each — iterates over all elements without index access, suitable for modern collections.Limitations and specifics of For Each:
Example:
Dim items As New List(Of Integer)({1, 2, 3}) For Each item As Integer In items Console.WriteLine(item) Next
Attempting to modify the collection inside the loop may cause an error:
For Each item As Integer In items If item = 2 Then items.Remove(item) ' Exception! End If Next
Can you modify collection elements by value using For Each if the elements are structs?
No, if the elements of the collection are structs (value types), the iteration variable in For Each contains a copy of the value. Any changes to the variable will not affect the actual element in the collection. For example:
Structure Point Public X As Integer End Structure Dim points As New List(Of Point)({New Point With {.X = 1}}) For Each pt In points pt.X = 100 ' Does not change points(0).X Next
Story
In the project, For Each was used to modify fields of employee structs. The iteration did not change the original data because the iteration object was a copy, not the actual element of the collection. As a result, salary updates did not work.
Story
During the iteration of a list in For Each, elements were removed in a condition—resulting in the application throwing an InvalidOperationException and crashing.
Story
Iterating over a collection using For Each without accounting for its mutability led to an infinite loop, as an external data source was filling this collection while it was being read, causing logical errors in calculations.