title: Can't add/remove items from a collection while foreach is iterating over it
body: <p>If I make my own implementation of <code>IEnumerator</code> interface, then I am able ( inside <code>foreach</code> statement )to add or remove items from a <code>albumsList</code> without generating an exception.But if <code>foreach</code> statement uses <code>IEnumerator</code> supplied by <code>albumsList</code>, then trying to add/delete ( inside the foreach )items from <code>albumsList</code> will result in exception:</p>
  
  <pre><code>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 &lt; 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;
          }
      }
  
  }
  </code></pre>
  
  <p>a) I assume code that throws  exception ( when using <code>IEnumerator</code> implementation <code>A</code> supplied by <code>albumsList</code> ) is located inside <code>A</code>? </p>
  
  <p>b) If I want to be able to add/remove items from a collection ( while <code>foreach</code> is iterating over it), will I always need to provide my own implementation of <code>IEnumerator</code> interface, or can albumsList be set to allow adding/removing items?</p>
  
  <p>thank you</p>