Problem finding substitute for foreach loop.

Currently I have a list called bulletlist. It is a 1 dimensional list. I use a foreach loop to iterate through the list:

foreach(Bullet bullet in bulletlist) // Cannot modify list meanwhile iterating { bullet.update(); } 

The problem is sometimes bullet.update() will delete the bullet from the list.

This causes the program to crash and throw a exception: 'System.InvalidOperationException' Additional information: Collection was modified; enumeration operation may not execute.

Because of this I am looking for a substitute that will not crash when bullet.update() deletes the object from the list.

Any suggestions?

Also I was wondering if I have a for loop:

for(int i = 0 ; i < x ; i++) { // Code } 

If I change x in the for loop will the program clash/stop/not work.

by vroomvsr via /r/csharp

Leave a Reply