Sign in to follow this  
Andy474

XNA InvalidOpperationException in foreach loop

Recommended Posts

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?

Share this post


Link to post
Share on other sites
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().

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this