On Jul 3, 12:07*am, Henri.Chinas... @googlemail.com wrote:
I have a feeling this is a dumb one, but here it is:
IEnumerator<Tim plements IDisposable, but the thing is I'm not sure
what I'm supposed to dispose!
It's very rare that you need to call Dispose yourself on an
IEnumerator<T>. It's more likely that you'll be using IEnumerable<T>
and the foreach statement. foreach automatically calls Dispose.
I'm also curious why IEnumerator<T>
implements IDisposable, but not IEnumerator.
An oversight, in my view. foreach already called Dispose if the
IEnumerator actually implemented IDisposable - but now the generic
version always does, which makes life simpler.
It allows iterators to work with resources which need cleaning up. As
an example, I have a LineReader class which implements
IEnumerable<str ing>. You construct it with a filename (or a delegate
which returns a TextReader when called) and when you start iterating,
it opens the file (or calls the delegate). However, if the caller
decides to stop iterating at some point before LineReader reaches the
end of the file, we still want to close it. The fact that foreach
calls Dispose makes this easy to achieve.
(This is the way that finally blocks work in iterator blocks in C# 2
and 3, by the way.)
Jon