1
foreach (var shotItem in Invadershots)// it points to me to there and doesnt allow me to loop.."{"Collection was modified; enumeration operation may not execute."}"
{
  shotItem.Move();// it happens when this simple method called (which actually checks some bool..if the shot was out of the winform).
  if (shotItem.removeShot)
  {
        Invadershots.Remove(shotItem);
  }
}

Could it be because i change the List items simultaneously?
How can i prevent that error from occurring?

razlebe
  • 7,134
  • 6
  • 42
  • 57
Dmitry Makovetskiyd
  • 6,942
  • 32
  • 100
  • 160

3 Answers3

5

This is because you trying modify collection Invadershots

Invadershots.Remove(shotItem);

This is not allowed within foreach, use for instead..

Andrew Orsich
  • 52,935
  • 16
  • 139
  • 134
3

You cannot alter a collection whilst enumerating across it. Create a clone of the collection and alter that.

Tomas McGuinness
  • 7,651
  • 3
  • 28
  • 40
1

You can't do that deleting an element into a List, that you'r reading in a foreach will crash, surely, try to make a copy to remove with that while you're in the foreach, or make a for iteration and control de number of elements correctly and the out condition.

See you

Amedio
  • 895
  • 6
  • 13