CSharp - Iterators and yield return

Introduction

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:

Demo

using System;
using System.Collections.Generic;

class Test{//  w  w  w. j a  va  2 s .co 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;
         }
     }
}

Result

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.