Junior · Explain · Lazy sequence ownership

Who owns the enumerators inside the lazy paired-stream operation, and what happens when the consumer stops early?

Think through your answer before opening the explanation.

Coding interviews

Reveal answer and reasoning

A lazy operation owns the enumerators it creates even when its consumer stops before the source ends. This paired-stream sum stops at the shorter input and disposes both enumerators through using declarations inside the iterator. Inputs are ordinary enumerable sequences, and the consumer takes only one output. The task concerns lifecycle and consumption boundaries, not another eager array-merge algorithm. The return value is an enumerable recipe; resources are acquired when enumeration begins.

Each call that obtains a new enumerator owns separate traversal state. The paired operation must release both acquired enumerators whether it reaches the shorter source, throws during addition or is disposed early by its consumer.

For p yielded pairs, work is O(p) with constant auxiliary iterator state, excluding resources owned by the sources. Because the condition advances the left side first, exhaustion of the right side can consume one extra left value. That detail matters for one-shot or side-effecting inputs. Consumption and production counts can differ at the shorter boundary. The left MoveNext executes before the right one, so an exhausted right side can leave one extra left value consumed but not yielded.

Reversing the condition would change which source can advance extra, not make the asymmetry disappear automatically.

What a strong answer covers

  • A lazy operation owns the enumerators it creates even when its consumer stops before the source ends.
  • Take one disposes the outer iterator when it stops.
  • For p yielded pairs, work is O(p) with constant auxiliary iterator state, excluding resources owned by the sources.

Common pitfall

Disposing an enumerable object is not the same as disposing the enumerators it creates. Returning a lazy query also extends source-resource lifetimes beyond method return. This sample does not make non-repeatable streams replayable or promise that no source side effect occurs during MoveNext.

Follow-up questions

  1. Use a shorter right sequence and count left-side MoveNext observations. Hint: left is evaluated first in the short-circuit condition. Then stop before the second output and verify both finally blocks still run.
  2. Which source can be advanced one extra time when the other source is exhausted, and why?

Self-review

Choose what to revisit. These marks are your own assessment and are separate from lesson completion.

Primary references

Open lesson and code ↗

← All interview questions