Skip to content

yield return and yield break

Question

Describe yield return and yield break.

Short interview answer

yield return produces the next element of an iterator sequence; yield break ends that sequence. The compiler generates the iterator machinery and execution is deferred until enumeration.

Detailed answer

An iterator method can expose values one at a time without constructing an entire collection first. Its local state is preserved between calls to the enumerator. Use yield return for lazy sequences; use yield break for an early normal end. Exceptions and resource lifetime still need deliberate handling.

Sources