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 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.
Because a yield break statement unconditionally transfers control elsewhere, the end point of a yield break statement is never reachable.