Collection was modified; enumeration operation may not execute. why?

208 views Asked by At

Sorry, I searched about this error but it's a different case and it doesn't help me...

I want to make a Spaceship Invasion Game and i made a list of all bullets as PicutreBox.

List<PictureBox> all_bullets = new List<PictureBox>();

When you press the Space button(fire button) a new bullet is created, added in the form control's and in the list all_bullets.

When the buttle goes from the form if (_bullet.Location.Y <= 0) the _bullet from this code(below) should be removed from the all_bullets list.

private void tmr_bullets_Tick(object sender, EventArgs e)
{
        foreach (PictureBox _bullet in all_bullets)
        {
            _bullet.Location = new Point(_bullet.Location.X, _bullet.Location.Y - 20);

            if (_bullet.Location.Y <= 0)
            {  all_bullets.Remove(_bullet);  }
        }

        nr_bullets.Text = Convert.ToString(all_bullets.Count);

Error:

Collection was modified; enumeration operation may not execute.

Sorry if it's re-posted but i didn't found what i need.

1

There are 1 answers

3
Hamid Pourjam On BEST ANSWER

You can not modify the collection while you are enumerating on it

all_bullets.Remove(_bullet);  

this will modify (delete an item from collection) while you are enumerating on it

you can use a hack to do this

foreach (PictureBox _bullet in all_bullets.ToList())