I have a generic Tree class which will implement ICollection< T > (and hence IEnumerable< T > and IEnumerable).
For this I have to implement a TreeEnumerator class.
Every call to Tree.GetEnumerator() will return a new instance of TreeEnumerator.
I have 2 questions:
-
If there are many TreeEnumerator objects floating around and the underlying Tree changes then what happens ? how to handle that ?
-
Is it better to do a CopyToArray all the tree elements (inside TreeEnumerator for easy array traversal) when TreeEnumerator is created or do the traversal one step at time with each MoveNext ?
I know CopyToArray is easy one time traversal but costs on space.
EDIT :
After getting to know of version mechanism:
Can you point to an example code of this versioning mechanism ? There must be standard naming and way to access , because foreach loop will need this check with each MoveNext
Usually, structural changes to the underlying collection invalidate any existing iterators. This can be implemented using a “version number” in the collection, which can be checked on each iteration step.
For example, from the docs for
List<T>.GetEnumerator():(In practice, it will throw
InvalidOperationException.)Note that the concurrent collections in .NET 4 explicitly allow the collection to be changed without invalidating the iterator. Typically the iterator will only see the original elements, as if a snapshot has been taken when
GetEnumerator()was called.