ProgrammingVB.NET Developer

How is the processing of For and For Each loops implemented in Visual Basic, when to choose one loop over the other, and what common errors occur when working with collections?

Pass interviews with Hintsage AI assistant

Answer.

In Visual Basic, there are For and For Each loops, each applicable for specific tasks.

Background

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.

Problem

The main issue is the incorrect choice of loop type and trying to modify a collection inside For Each, leading to runtime errors.

Solution

Use a standard For loop when:

  • an index of the element is needed
  • elements of an array need to be modified by index
  • iteration over a range of numbers is required

Apply For Each when:

  • only the value of each element is important
  • the structure of the collection is unknown beforehand
  • elegance and error minimization are needed

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:

  • For is used for index-based operations
  • For Each cannot modify the collection itself within the loop
  • For Each is universal for any IEnumerable object

Trick questions.

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.

Common errors and anti-patterns

  • Modifying a collection during For Each
  • Confusing indexes when using standard For with arrays and collections
  • Using For Each when an index of the element is needed

Real-life example

** Negative case

A developer tries to delete elements from List(Of T) inside For Each. An InvalidOperationException error occurs during runtime.

Pros:

  • Simple code for reading a collection

Cons:

  • The program crashes

** 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:

  • No iteration errors, all required elements are removed

Cons:

  • Requires more code and understanding of data structures