Friday, April 11, 2014

Yield statement

Yield keyword is used in an iterator block to calculate the value for the enumerator object.


Can be understand by an example


1. class Program
2. {
3.        static void Main(string[] args)
4.        {
5.            foreach (int i in GetInt())
6.                Console.WriteLine("Got " + i.ToString());
7.        }
8.        public static IEnumerable<int> GetInt()
9.        {
10.            for (int i = 0; i < 5; i++)
{
11.               yield return i;

if(i==3)
yield break;

}
12.        }
}



As soon as control reach at line no 11 for i=0. It returns the value of i to caller.
And control reached to line no 5 again thereafter print its value.


Again call the same function GetInt but this time loop does not start from starting it start from where we have leave it i.e for i=1 and again when it reach to line no 11 it returns the value of i to caller. This process repeat until the GetInt() loop ends.


So output will be


0
1
2
3
4


This output we can without using yield statement but main point is that while using yield no need to iterate the whole loop if not required.



No comments:

Followers

Link