Monday, April 19, 2010

04/19 : Fibonacci With yield In C#

 

yield syntax is a feature of FW 2.0.

  • It is used to return a item inside of a loop and keep state of calling method through multiple calls
  • can be used in function like power , Fibonacci which need the previous value to calculate current result
  • The function need to return IEnmerable<T>
  • yield return ; yield break
    • yield break will not return any value and stop
  • Calling function use foreach
  • Sample Code

……………………………….

public static IEnumerable<int> Fibonacci(int max)
       {
           if (max < 1)
           {
               yield break;
           }

           yield return 0;
           yield return 1;
           int counter = 0;
           int beforeprevious = 0;
           int previous = 1;
           int current = int.MinValue;
           while (counter++ < max)
           {
               current = beforeprevious + previous;
               yield return current;
               beforeprevious = previous;
               previous = current;
           }
       }

………………(calling funtion)

foreach (int jj in Fibonacci(10))
{
    Console.Write(jj.ToString() + "  "); 
}

0 Comments:

Post a Comment

<< Home