Dmitry Makovetskiyd
Dmitry Makovetskiyd

Reputation: 7053

Why am I getting an InvalidOperationException?

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?

Upvotes: 1

Views: 187

Answers (3)

Amedio
Amedio

Reputation: 895

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

Upvotes: 1

Andrew Orsich
Andrew Orsich

Reputation: 53675

This is because you trying modify collection Invadershots

Invadershots.Remove(shotItem);

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

Upvotes: 5

Tomas McGuinness
Tomas McGuinness

Reputation: 7691

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

Upvotes: 3

Related Questions