Question history
The For...Next loop has existed in Visual Basic since its early versions, allowing iteration over a range of values, often used for working with arrays and collections. In VB.NET, a semantically stricter counter and support for step (Step) were added.
Problem
A classic mistake is modifying the loop counter (e.g., i), which leads to erroneous behavior: the counter is still automatically incremented/decremented at the end of each iteration. It's also important to properly set the boundaries for iterating over collections (e.g., For i = 0 To arr.Length - 1).
Solution
Always use immutable counters or immediately place the upper boundary expression in a variable if the collection might change within the loop. Do not explicitly change the counter variable in the loop body.
Example code:
Dim arr() As Integer = {1, 2, 3, 4} For i As Integer = 0 To arr.Length - 1 Console.WriteLine(arr(i)) Next
Key features:
What happens if you manually change the counter in the loop body?
The value will really change only within the current iteration, but at the end of the iteration, Visual Basic will automatically perform the increment/decrement, leading to unpredictable pass counts.
For i = 1 To 5 If i = 3 Then i = 1 Console.WriteLine(i) Next
Can you use For...Next to iterate over collections like List(Of T)?
Yes, but it's preferable to use For Each for collections to avoid errors with changing sizes. For...Next only stores indices.
What happens if the upper boundary is less than the lower in a positive step?
The loop will not execute at all.
For i = 5 To 1 ' without Step - the loop will not execute ... Next
The counter was manually changed upon encountering a specific element, trying to skip future elements led to missing some iterations and an infinite loop.
Pros:
Cons:
Using a separate variable to control conditions, no interference with the loop counter.
Pros:
Cons: