Here is a sample code to retrieve data from a database using the yield keyword that I found in a few place while googling around :
public IEnumerable
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.