T
Tim Davis
I am currently writing a class which I would like to make "enumerable" by
inheriting from IEnumerable. The documentation says that the
IEnumerator.MoveNext method should throw an exception if the object being
enumerated has changed since the enumerator was created. Does anyone have
any tips on how best to implement this?
I can think of 2 approaches, neither of which seem very satisfactory. These
are as follows:
1. Take a copy of the class being enumerated when the enumerator is created.
This would be a complete copy, not just a copy of the reference. Then, every
time MoveNext is called, it could compare the current contents to that when
the enumerator was created. This would have a potentially enormous overhead.
2. Have the class being enumerated keep a list of all currently live
enumerators. The class would then inform the enumerators if its contents
changed. This seems like a lot of work to implement something which you
might expect to be straightforward.
An alternative would be to not bother throwing this exception at all.
However this would then break the IEnumerable and IEnumerator specification
which might be considered bad practice.
Thanks,
Tim Davis
inheriting from IEnumerable. The documentation says that the
IEnumerator.MoveNext method should throw an exception if the object being
enumerated has changed since the enumerator was created. Does anyone have
any tips on how best to implement this?
I can think of 2 approaches, neither of which seem very satisfactory. These
are as follows:
1. Take a copy of the class being enumerated when the enumerator is created.
This would be a complete copy, not just a copy of the reference. Then, every
time MoveNext is called, it could compare the current contents to that when
the enumerator was created. This would have a potentially enormous overhead.
2. Have the class being enumerated keep a list of all currently live
enumerators. The class would then inform the enumerators if its contents
changed. This seems like a lot of work to implement something which you
might expect to be straightforward.
An alternative would be to not bother throwing this exception at all.
However this would then break the IEnumerable and IEnumerator specification
which might be considered bad practice.
Thanks,
Tim Davis