Using yield to iterate over a datareader might not close the connection?
Connection will be closed automatically since you're using it inside "using" block.
The Iterator that the compiler synthesises implements IDisposable
, which foreach
calls when the foreach
loop is exited.
The Iterator's Dispose()
method will clean up the using
statements on early exit.
As long as you use the iterator in a foreach
loop, using()
block, or call the Dispose()
method in some other way, the cleanup of the Iterator will happen.