Can't add/remove items from a collection while foreach is iterating over it
Posted
by flockofcode
on Stack Overflow
See other posts from Stack Overflow
or by flockofcode
Published on 2010-06-14T20:51:22Z
Indexed on
2010/06/14
21:02 UTC
Read the original article
Hit count: 208
c#
|ienumerable
If I make my own implementation of IEnumerator
interface, then I am able ( inside foreach
statement )to add or remove items from a albumsList
without generating an exception.But if foreach
statement uses IEnumerator
supplied by albumsList
, then trying to add/delete ( inside the foreach )items from albumsList
will result in exception:
class Program
{
static void Main(string[] args)
{
string[] rockAlbums = { "rock", "roll", "rain dogs" };
ArrayList albumsList = new ArrayList(rockAlbums);
AlbumsCollection ac = new AlbumsCollection(albumsList);
foreach (string item in ac)
{
Console.WriteLine(item);
albumsList.Remove(item); //works
}
foreach (string item in albumsList)
{
albumsList.Remove(item); //exception
}
}
class MyEnumerator : IEnumerator
{
ArrayList table;
int _current = -1;
public Object Current
{
get
{
return table[_current];
}
}
public bool MoveNext()
{
if (_current + 1 < table.Count)
{
_current++;
return true;
}
else
return false;
}
public void Reset()
{
_current = -1;
}
public MyEnumerator(ArrayList albums)
{
this.table = albums;
}
}
class AlbumsCollection : IEnumerable
{
public ArrayList albums;
public IEnumerator GetEnumerator()
{
return new MyEnumerator(this.albums);
}
public AlbumsCollection(ArrayList albums)
{
this.albums = albums;
}
}
}
a) I assume code that throws exception ( when using IEnumerator
implementation A
supplied by albumsList
) is located inside A
?
b) If I want to be able to add/remove items from a collection ( while foreach
is iterating over it), will I always need to provide my own implementation of IEnumerator
interface, or can albumsList be set to allow adding/removing items?
thank you
© Stack Overflow or respective owner