Monday, 3 October 2011

ienumerable in c#

           We all are very familiar with foreach method is c# that returns a result per iteration.  Ienumeration is used to create user defined function which is used with foreach loop.

Example:
          I want to get the numbers between 2 values using a function get_numbers(int min,int max).

                  foreach(int n in get_nubers(10,30))
                 {
                    Console.WriteLine(n);
                  }

                   IEnumerable<int> get_numbers(int min, int max)
                  {
                     for (; min <= max; min++)
                     {
                        yield return min;
                      }
                   }

         In the above example we have a new keyword yield  it is a special type of return because the foreach method calls the function at each iteration i.e

          n <--- get_numbers(10,30)  then the control passed to the method and get the number 10  then returned to the called function.  Again the function called for the next iteration.

         Simply set a break point in the foreach statement and check the flow.

         

                   

       

No comments:

Post a Comment