yield Statement in C#

 

The yield statement is used in an iterator block to yield a value to the enumerator object or to signal the end of the iteration.

 

The yield keyword is used to specify the value (or values) to be returned to the caller’s for each construct. When the yield return statement is reached, the current location is stored, and execution is restarted from this location the next time the iterator is called.

 

public IEnumerator GetEnumerator() 

{ 

            foreach (Book c in bookArray) 

            { 

                yield return c; 

            } 

}

 

GetEnumerator() iterates over the sub items using internal foreach logic and returns each Book to the caller using the yield return syntax.

 

A yield return statement is executed as follows. 

  • The expression given in the statement is evaluated, implicitly converted to the yield type, and assigned to the Current property of the enumerator object.
  • Execution of the iterator block is suspended. If the yield return statement is within one or more try blocks, the associated finally blocks are not executed at this time.
  • The MoveNext method of the enumerator object returns true to its caller, indicating that the enumerator object successfully advanced to the next item.

 

The next call to the enumerator object's MoveNext method resumes execution of the iterator block from where it was last suspended.

 

A yield break statement is executed as follows. 

  • If the yield break statement is enclosed by one or more try blocks with associated finally blocks, control is initially transferred to the finally block of the innermost try statement. When and if control reaches the end point of a finally block, control is transferred to the finally block of the next enclosing try statement. This process is repeated until the finally blocks of all enclosing try statements have been executed.
  • Control is returned to the caller of the iterator block. This is either the MoveNext method or the Dispose method of the enumerator object.

 

Because a yield break statement unconditionally transfers control elsewhere, the end point of a yield break statement is never reachable.