# For Each Loop

How do you know what iteration you are up to in a For Each loop when ‘s’ is not an integer?
As I want to remove the object I have collided with

Dim squareRect As Rect
For Each s As Square In Squares
s.DrawImage(g)
If LastTouchPoint <> Nil Then
squareRect = New Rect(s.X, s.Y-40, s.Width, s.Width
Dim intersect As Rect = touchRect.Intersection(squareRect)
If intersect <> Nil Then
Squares.remove(??)
Exit
// Game over
'GameOver = True
End If
End If
Next

You can add one variable to hold the array index.

``````Dim squareRect As Rect
dim i as integer
For Each s As Square In Squares
s.DrawImage(g)
If LastTouchPoint <> Nil Then
squareRect = New Rect(s.X, s.Y-40, s.Width, s.Width
Dim intersect As Rect = touchRect.Intersection(squareRect)
If intersect <> Nil Then
Squares.remove(i)
Exit
// Game over
'GameOver = True
End If
End If
i = i+1
Next``````

Or

``````Dim squareRect As Rect
dim i as integer
For i=0 Squares.ubound
dim s As Square = Squares(i)
s.DrawImage(g)
If LastTouchPoint <> Nil Then
squareRect = New Rect(s.X, s.Y-40, s.Width, s.Width
Dim intersect As Rect = touchRect.Intersection(squareRect)
If intersect <> Nil Then
Squares.remove(i)
Exit
// Game over
'GameOver = True
End If
End If
Next``````

When you remove elements from an array in a For… Next loop, you should not loop from 0 to Ubound as you could get unpredictable results. The correct way to do it is:

```For i As Integer = arr.Ubound DownTo 0 ... arr.Remove(i) ... Next```

Do not use For Each … Next. Check the docs at For Each … Next:

Thanks Eli and Asis

I use For Each a lot and never had any issues with it. In fact, I always thought thats the correct way to do.
Good to know it is not recommended. So will switch back to the FOR … NEXT

[quote=308195:@Christoph De Vocht]I use For Each a lot and never had any issues with it. In fact, I always thought thats the correct way to do.
Good to know it is not recommended. So will switch back to the FOR … NEXT[/quote]
As long as you’re not using array.remove function inside the loop, it’s save to use.

it’s ok as long if you remove then exit immediately

You can see the exit statement after remove. Hence, for this case is not harm to use this looping. But, it’s another story if the OP then remove the exit function.

I just worked on a case where the user can select and/or deselect multiple items from a list (iOS table) before committing. I use the For Each loop with the i = i + 1 counter to find if a selection already exists and should be deleted. I use booleans to indicate add or deletion. After the loop exits I test the booleans to see if I should add or delete items to the array. So I don’t modify the array within the For Each loop.