Is there any way in a C# iterator block to provide a block of code which will be run when the foreach ends (either naturally of by being broken out of), say to clean up resources?
The best I have come up with is to use the using construct, which is fine but does need an IDisposable class to do the clean up. For example:
public static IEnumerable<string> ReadLines(this Stream stream)
{
using (StreamReader rdr = new StreamReader(stream))
{
string txt = rdr.ReadLine();
while (txt != null)
{
yield return txt;
txt = rdr.ReadLine();
}
rdr.Close();
}
}