[Mono-list] IEnumerators

John Barnette jbarn@httcb.net
Tue, 17 Jul 2001 02:02:45 -0600


> IEnumerator.MoveNext() has to throw
> InvalidOperationException if the object it's
> enumerating is modified in any way.  I tested this
> with MS's implementation of BitArray, and it seems to
> really detect *any* change to the original object.
>
> Maybe my brain is fried, but I can't seem to think
> of a great way to implement this.  The best way I can
> think of is to have the original object keep a change
> count.  Whenever any call modifies the object,
> increment the count.  The IEnumerator will store
> the value on creation, then check it every time you
> call MoveNext().

That's the standard way to do it in most languages:

public class Foo : IEnumerable {
	private string[] strings;
	private int modCount = 0;

	...

	public virtual void SetString(int index, string value) {
		modCount++;
		strings[index] = value;
	}

	...

	private class FooEnumerator : IEnumerator {
		private Foo f;
		private int myModCount;

		public FooEnumerator(Foo f) {
			this.f = f;
			myModCount = f.modCount;
		}

		public object Current {
			...

			if (myModCount != modCount) {
				throw new InvalidOperationException();
			}
		}

		...
	}
}


I know this is a pretty sketchy example: I'm away from all my code (and C#
references ;-).  If you want a more specific example, just ask.


~ j.