By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
454,421 Members | 1,386 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 454,421 IT Pros & Developers. It's quick & easy.

IEnumerator<T> and IDisposable: what to dispose?

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

IEnumerator<Timplements 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
Jul 2 '08 #1
Share this Question
Share on Google+
2 Replies


P: n/a
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:am*****@gmail.com; blog:devkids.blogspot.com
Jul 3 '08 #2

P: n/a
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<Timplements 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<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
Jul 3 '08 #3

This discussion thread is closed

Replies have been disabled for this discussion.