Well, the question was originally tagged C #, now deleted. but....
It is not true that there is no for / for loop if you remove an item from the collection. If you delete items while moving forward, you will have problems indexing items after you delete, because the index no longer matches your next item. You avoid for / loop issues only if you loop in reverse order (from last element to first)
In foreach, the same problem internally arises. The enumerator supports the Current element for the element, if you delete the element and then move to the Next position, the Current indexer does not point to the element after deletion, but to the 2 element of the position after deletion.
For instance:
Suppose a set of strings of "birds", "animals" and "fish"
- When starting foreach, the internal current is 0 (indicates "birds")
- you remove the “birds”, so the “animals” are at index 0 (where the current still indicates)
- You move on to the next element (Current = 1, indicates "fish")
- Without exception, the subsequent transition from the cycle will end.
foreach was not designed to allow this scenario.
Steve source share