XNA InvalidOpperationException in foreach loop

Started by
1 comment, last by Andy474 14 years, 10 months ago
ok, the purpose of this code is to remove all Bullets and Soldiers on the map once certain event are triggered

THIS IS THE ENTIRE VOID"
private void Cleanup()
        {
            if (Bulletlist.Count > 0)
            {
                foreach (Bullet bullet in Bulletlist) // 'in' causes Error
                    Bulletlist.Remove(bullet);
            }
            if (NPCList.Count > 0)
            {
                foreach (NPC soldier in NPCList)
                    NPCList.Remove(soldier);
            }
        }
when i run this code and execute this method I get an InvalidOperationException at the Keyword 'in' and i cant figure out why this is tripping Any ideas?
Advertisement
You cannot modify a list you are enumerating. Furthermore, just set the list to null, or create a new list in its place and let the GC deal with cleaning up your discarded list of bullets and soldiers, or call List.Clear().

In time the project grows, the ignorance of its devs it shows, with many a convoluted function, it plunges into deep compunction, the price of failure is high, Washu's mirth is nigh.

Beautiful. thanks :)

This topic is closed to new replies.

Advertisement