Rauld
Rauld

Reputation: 990

Prevent collection from being modified while enumerating

how do i prevent Collection from being modified during Enumeration.

Here is the class source code.

 public class cars : IEnumerator,IEnumerable
 {
  private car[] carlist;
  int position = -1;

  public IEnumerator GetEnumerator()
  { return (IEnumerator)this; }

  public bool MoveNext()
  {
     position++;
     return (position < carlist.Length);
  }

  public void Reset()
  {position = 0;}

  //IEnumerable
  public object Current
  { get { return carlist[position];}
  }
 }      

Upvotes: 0

Views: 248

Answers (2)

Xharlie
Xharlie

Reputation: 2540

Firstly, your collection class should not implement IEnumerator – it should implement IEnumerable only and return an instance of another class that implements IEnumerator (possibly carEnumerator) when GetEnumerator() is called.

IEnumerator (implemented in carEnumerator) extends IDisposable so, in cars.GetEnumerator(), you can set a private flag (perhaps private bool isEnumerating) to true. In carEnumerator, keep a reference to the collection (cars) and, in carEnumerator.Dispose(), set isEnumerating back to false.

Finally, in all the methods in cars that you want to disable while enumeration is ongoing, check the state of isEnumerating and throw an exception or do nothing if it is true.

Upvotes: 1

Richard
Richard

Reputation: 108975

At least some of the BCL collections do this by including a version counter. Each modification of the collection increments the counter. When an enumeration of the collection is started the current value of the version count is kept. On each call to the enumerator's MoveNext the underlying collection's version is checked against the kept counter, if different an exception is thrown.

Upvotes: 0

Related Questions