In Visual Basic, there are For and For Each loops, each applicable for specific tasks.
VB6 and classic Visual Basic supported only range-based loops (For ... Next). In later versions (starting from VB6 and VB.NET), For Each was introduced, allowing for elegantly iterating through collection and array elements.
The main issue is the incorrect choice of loop type and trying to modify a collection inside For Each, leading to runtime errors.
Use a standard For loop when:
Apply For Each when:
Code example:
' Iterating through elements with modification Dim arr() As Integer = {1, 2, 3} For i As Integer = 0 To arr.Length - 1 arr(i) = arr(i) * 2 Next ' Read-only collection Dim list As New List(Of String) From {"one", "two", "three"} For Each s As String In list Console.WriteLine(s) Next
Key features:
Can you modify a List(Of T) collection inside For Each?
No. This will lead to an InvalidOperationException because the structure of the collection should not change during iteration.
How to exit For Each early?
Use the Exit For statement when the required element is found.
For Each s In list If s = "two" Then Exit For End If Next
What is the speed difference between For and For Each for arrays?
Usually, the difference is minimal, but For may be slightly faster (especially for primitive type arrays) because it works directly with indexes, while For Each creates an additional enumerator object.
** Negative case
A developer tries to delete elements from List(Of T) inside For Each. An InvalidOperationException error occurs during runtime.
Pros:
Cons:
** Positive case
To delete elements, iteration is performed from the end using a standard For:
For i = list.Count - 1 To 0 Step -1 If list(i) = "two" Then list.RemoveAt(i) End If Next
Pros:
Cons: