Lecture overview -- Keyboard shortcut: 'u'  Previous page: Making iterators with yield return -- Keyboard shortcut: 'p'    Lecture notes - all slides and notes together  slide -- Keyboard shortcut: 't'  Help page about these notes  Alphabetic index  Course home  Page 36 : 36
Object-oriented Programming in C#
Collection Classes
Iterator blocks and yield return

Iterators are implemented by methods made with iterator blocks

IEnumerator<Type> Method() { // iterator block
  Type t;

  ...
  yield return t;
  ...
}

A method formed by an iterator block.

  • Characteristics

    • The return type of the method must be an enumerator or an enumerable

    • A method with an iterator block is not executed immediately when calling it

    • Instead an enumerable object is created and returned

    • Execution starts when MoveNext is activated on the enumerable object

The compiler transforms a method with an iterator block to an underlying state machine which manages the traversal

Go to exerciseInfinite Collections of Integers