Advertisement
Intermediate C#, Iterators & yield return

How does an iterator method interact with try/finally, and when does the finally block actually execute given the method's lazy, on-demand nature?

Short answer

A finally block inside an iterator runs when iteration COMPLETES NORMALLY, when 'yield break' is hit, OR when the consumer disposes the enumerator early (like breaking out of a foreach loop, which implicitly calls Dispose()) — ensuring cleanup code (like closing a resource)…

Save C# mock interview
Advertisement
AModel answer
A finally block inside an iterator runs when iteration COMPLETES NORMALLY, when 'yield break' is hit, OR when the consumer disposes the enumerator early (like breaking out of a foreach loop, which implicitly calls Dispose()) — ensuring cleanup code (like closing a resource) reliably runs regardless of how iteration actually ends.
public IEnumerable<string> ReadLinesLazily(string path) {
  using var reader = new StreamReader(path);
  string? line;
  while ((line = reader.ReadLine()) != null) {
    yield return line;
  }
  // the 'using' reader is disposed correctly even if the consumer breaks out of foreach early
}
Real-world example
Guaranteeing a file handle or database cursor is properly closed even if the consumer only reads a few lines before breaking out of the loop.
Likely follow-ups
  • How does a 'using' statement inside an iterator method get compiled differently to support this deferred cleanup behavior?
Related topics