If I make my own implementation of IEnumerator
interface, then I am able ( inside foreach
statement )to add or remove items from a albumsList
Generally it's discouraged to design collection classes that allow you to modify the collection while enumerating, unless your intention is to design something thread-safe specifically so that this is possible (e.g., adding from one thread while enumerating from another).
The reasons are myriad. Here's one.
Your MyEnumerator
class works by incrementing an internal counter. Its Current
property exposes the value at the given index in an ArrayList
. What this means is that enumerating over the collection and removing "each" item will actually not work as expected (i.e., it won't remove every item in the list).
Consider this possibility:
The code you posted will actually do this:
Current
of "rock." You remove "rock."["roll", "rain dogs"]
and you increment your index to 1, making Current
equal to "rain dogs" (NOT "roll"). Next, you remove "rain dogs."["roll"]
, and you increment your index to 2 (which is > Count
); so your enumerator thinks it's finished.There are other reasons this is a problematic implementation, though. For instance someone using your code might not understand how your enumerator works (nor should they -- the implementation should really not matter), and therefore not realize that the cost of calling Remove
within a foreach
block incurs the penalty of IndexOf
-- i.e., a linear search -- on every iteration (see the MSDN documentation on ArrayList.Remove to verify this).
Basically, what I'm getting at is: you don't want to be able to remove items from within a foreach
loop (again, unless you're designing something thread-safe... maybe).
OK, so what is the alternative? Here are a few points to get you started:
Clear
(to remove all items) or RemoveAll
(to remove items matching a specified filter).ArrayList
already has a Clear
method, as do most of the collection classes you might use in .NET. Otherwise, if your internal collection is indexed, a common method to remove multiple items is by enumerating from the top index using a for
loop and calling RemoveAt
on indices where removal is desired (notice this fixes two problems at once: by going backwards from the top, you ensure accessing each item in the collection; moreover, by using RemoveAt
instead of Remove
, you avoid the penalty of repeated linear searches).ArrayList
to begin with. Go with strongly typed, generic counterparts such as List(Of Album)
instead (assuming you had an Album
class -- otherwise, List(Of String)
is still more typesafe than ArrayList
).