Newbie question.... does Remove() invalidate an enumeration?

  • Thread starter Thread starter Brian Muth
  • Start date Start date
B

Brian Muth

ArrayList al;
// populate the al

p = (MyObject) al[0]; // assuming it exists

// Try to remove duplicates...
foreach (MyObject q in al)
{
if (/* some conditional that determines what a duplicate is */)
al.Remove (q); // does this invalidate subsequent calls to
Remove()?
}

Thanks

B
 
Brian Muth said:
ArrayList al;
// populate the al

p = (MyObject) al[0]; // assuming it exists

// Try to remove duplicates...
foreach (MyObject q in al)
{
if (/* some conditional that determines what a duplicate is */)
al.Remove (q); // does this invalidate subsequent calls to
Remove()?

Changing the collection results in an invalid enumeration, so the call to
remove will probably cause the IEnumerator implementation in al to throw an
exception(ArrayList will, I'm quite sure, but hand written collections might
not).

You should either add the members you want to remove to another list or use
a for loop, starting at the end and moving towards the beginning so that
removing items doesn't cause your indexes to get screwed up.
 
Back
Top