Advertisement
Advanced C#, Iterators & yield return

How would you write a custom iterator that safely handles resource cleanup for a lazily-enumerated database cursor, ensuring the connection is closed even if enumeration is abandoned early?

Short answer

Wrap the resource acquisition in a 'using' statement (or try/finally) directly within the iterator method body — the compiler-generated state machine correctly ensures this cleanup logic runs whenever the enumerator is disposed, which happens automatically at the end of a normal…

Save C# mock interview
Advertisement
AModel answer
Wrap the resource acquisition in a 'using' statement (or try/finally) directly within the iterator method body — the compiler-generated state machine correctly ensures this cleanup logic runs whenever the enumerator is disposed, which happens automatically at the end of a normal foreach OR when a foreach loop is exited early via break/return/exception.
public IEnumerable<Row> QueryRows(string sql) {
  using var connection = new SqlConnection(connectionString);
  connection.Open();
  using var command = new SqlCommand(sql, connection);
  using var reader = command.ExecuteReader();
  while (reader.Read()) {
    yield return MapRow(reader);
  } // connection, command, and reader are all safely disposed, even if the consumer breaks out early
}
Real-world example
Ensuring a database connection is reliably closed even when a consumer only needs the first few rows and breaks out of the enumeration early.
Likely follow-ups
  • What subtle bug can occur if resource acquisition happens BEFORE the first yield, versus lazily on the first MoveNext() call?
Related topics