Iterators - CSharp Collection

CSharp examples for Collection:Iterator

Introduction

A foreach statement is a consumer of an enumerator.

An iterator is a producer of an enumerator.

A return statement says "Here's the value,"

A yield return statement says "Here's the next element."

On each yield statement, control is returned to the caller, but the callee's state is maintained.

In this example, we use an iterator to return a sequence of Fibonacci numbers.

Each fibonacci numbers is the sum of the previous two.

Demo Code

using System;/*from   w ww.  j  a  v  a  2s .c  om*/
using System.Collections.Generic;
class Test
{
   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


Related Tutorials