Thursday 28 July 2011

Beware the yield'd iterator

In C# there are two types of iterator (as far as I know). One is an iterator into a container which is created by something akin to List<T>.GetEnumerator(). The other is the yield'd iterator and this is created by a function which yield returns each element in the sequence.

The issue is that the former can be reset but the latter cannot. Therefore, if you are using the latter you need to be very sure that it is only used the once. If a second loop through the sequence will be required then store the iterator in a list comme ca


List<T> l = new List<T>(myIterator);


and then use l instead.

No comments:

Post a Comment