On this article ( http://blogs.msdn.com/oldnewthing/archive/2008/08/13/8854601.aspx), there is a pop question about iterators and one concerning a corner case:
Exercise: Consider the following
fragment: foreach (int i in
CountTo100Twice()) { … }Explain what happens on the 150th call
to MoveNext() in the above loop.
Discuss its consequences for recursive
enumerators (such as tree traversal).
I haven’t run this code, but I am assuming that this is a question supposedly with an answer from the articles (all links provided below), but I can’t find the answer in the knowledge shared by the article or in the comments for this particular article.
Does anyone know what the answer is? What other corner cases are there?
1) http://blogs.msdn.com/oldnewthing/archive/2008/08/12/8849519.aspx
2) http://blogs.msdn.com/oldnewthing/archive/2008/08/13/8854601.aspx
3) http://blogs.msdn.com/oldnewthing/archive/2008/08/14/8862242.aspx
4) http://blogs.msdn.com/oldnewthing/archive/2008/08/15/8868267.aspx
Thanks
I suspect he may be referring to the fact that each call to
MoveNext()invokes a state machine which in turn invokesMoveNext()on another state machine, making it all a bit inefficient.This is blogged about here by Wes Dyer and here by Eric Lippert.
The main corner case I’d say with iterator blocks is that nothing is executed before the first call to
MoveNext(). So this method:doesn’t actually throw the exception until you start iterating. Instead, you need to write something like this:
Again, Eric has blogged on this: part 1, part 2. I’ve blogged a suggestion to make life easier too, although I doubt it’ll ever come to anything.