Fortunately, as developers we don??™t need to care much about the hoops the compiler
has to jump through. However, there are a few quirks about the implementation
that are worth knowing about:
?– Before MoveNext is called for the first time, the Current property will always
return null (or the default value for the relevant type, for the generic interface).
?– After MoveNext has returned false, the Current property will always return the
last value returned.
?– Reset always throws an exception instead of resetting like our manual implementation
did. This is required behavior, laid down in the specification.
?– The nested class always implements both the generic and nongeneric form of
IEnumerator (and the generic and nongeneric IEnumerable where appropriate).
Failing to implement Reset is quite reasonable??”the compiler can??™t reasonably work
out what you??™d need to do in order to reset the iterator, or even whether it??™s feasible.
Arguably Reset shouldn??™t have been in the IEnumerator interface to start with, and I
certainly can??™t remember the last time I called it.
Implementing extra interfaces does no harm either. It??™s interesting that if your
method returns IEnumerable you end up with one class implementing five interfaces
173 Real-life example: iterating over ranges
(including IDisposable). The language specification explains it in detail, but the
upshot is that as a developer you don??™t need to worry.
Pages:
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346