IEnumerator<T> and IDisposable: what to dispose?

  • Thread starter Thread starter Henri.Chinasque
  • Start date Start date
H

Henri.Chinasque

I have a feeling this is a dumb one, but here it is:

IEnumerator<T> implements IDisposable, but the thing is I'm not sure
what I'm supposed to dispose! I'm also curious why IEnumerator<T>
implements IDisposable, but not IEnumerator.

Anyone?

Thanks,
HC
 
Hi

To have possibility to safely enumerate resource-based data, such as DataReader,
on common scenarious (like foreach). On other cases empty method does not
heavily implact on performance.

Regards, Alex Meleta
mailto:[email protected]; blog:devkids.blogspot.com
 
I have a feeling this is a dumb one, but here it is:

IEnumerator<T> implements 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
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<string>. 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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top