CSharp - Iterators and yield return


An iterator is a producer of an enumerator.

In this example, we use an iterator to return a sequence of Fibonacci numbers where each number is the sum of the previous two:


using System;
using System.Collections.Generic;

class Test{/*w  w w .ja v  a  2s .c  o  m*/
     static void Main(){
         foreach (int fib in Fibs(6))
           Console.Write (fib + "  ");

     static IEnumerable<int> Fibs (int fibCount){
         for (int i = 0, prevFib = 1, curFib = 1; i < fibCount; i++){
            yield return prevFib;
            int newFib = prevFib+curFib;
            prevFib = curFib;
            curFib = newFib;


A yield return statement returns the next element you need from this enumerator.

On each yield statement, control is returned to the caller, but its state is maintained to get the next property element.

The lifetime of this state is bound to the enumerator.