An iterator block could contain a series of yield statements to return individual elements of a sequence.
1 2 3 4 5 6 | private static IEnumerable<Dog> ListOfDogs() { yield return new Dog( "Jack" , 17); yield return new Dog( "Kirby" , 14); yield return new Dog( "Lassie" , 72); } |
More commonly, however, an iterator block will contain a loop that generates a sequence, with a yield statement that returns a new element of the sequence each time through the loop.
The example below returns a portion of the Fibonacci sequence, with each element in the sequence after the first two returned by a yield statement within the loop.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | static void Main() { foreach ( int i in Fibonacci(20)) Console.WriteLine(i); } private static IEnumerable< int > Fibonacci( int numInSeq) { yield return 0; yield return 1; int last = 0; int current = 1; for ( int i = 0; i < (numInSeq - 2); i++) { int next = last + current; yield return next; last = current; current = next; } } |