IDictionaryEnumerator approach

  • Thread starter Thread starter Wavemaker
  • Start date Start date
W

Wavemaker

I'm writing a class that implements the IDictionary interface. Along
with this, I'm implementing an IDictionaryEnumerator class. For the
IDictionaryEnumerator, the documentation says the following:

"An enumerator remains valid as long as the collection remains
unchanged. If changes are made to the collection, such as adding,
modifying or deleting elements, the enumerator is irrecoverably
invalidated and the next call to MoveNext or Reset throws an
InvalidOperationException."

So any IDictionaryEnumerator object needs to be notified when its
related collection is changed in some way.

I was thinking about implementing this using an event. Whenever the
collection is changed, it triggers the event. Each time an
IDictionaryEnumerator is created, it registers itself with the
event so that it will be notified when its collection has changed
and can invalidate itself.

When an IDictionaryEnumerator recieves notification that the
collection has changed, it sets an flag to indicate that it's
invalid and also removes itself from the collection's invalidate
event so that it will not be notified more than once.

Make sense?
 
You could do this but there may be a more elegant way. This is the way the
..NET collections and dictionaries work.

Each collection has a version variable (no relation to the assembly
versions). When the collection changes, the version is incremented. So the
version might start at zero, you add an element, now the version is one, and
so on.

When you instantiate the IDictionaryEnumerator, you could pass in the
dictionary instance and the enumerator could record the version for later
reference.

Now, on each access of the enumerator you would check the version from when
the enumerator was created with the current version on the dictionary
object. If they are the same, no changes have been made. A lot less
overhead than firing events.
 
Too much work. Try:

Adding a version field to the collection & enumerator.
Increment the collection version on every change.
Set the enumerator version during construction.
Now just compare versions in MoveNext or Reset.
 
:

Now, on each access of the enumerator you would
check the version from when the enumerator was
created with the current version on the dictionary
object. If they are the same, no changes have
been made. A lot less overhead than firing events.

This is much more elegant. Thank you! And thanks to the others who
have made the same suggestion.
 
Back
Top