An easy way to understand the yield keyword is that we don’t need an extra class to store the iteration result when returning using return return. Usually, when we iterate over a collection and want to return the result, we use the collection object to save the result. Consider an example.
public static Multiplication List (int number, int times)
{ List<int> resultList = new List<int>(); int result = number; for(int i=1;i<=times;i++) { result=number*i; resultList.Add(result); } return resultList; }
static void Main (string [] args)
{ foreach(int i in Multiplication(2,10)) { Console.WriteLine(i); } Console.ReadKey(); }
In the above example, I want to return the result of multiplication by 2 times. Therefore, I create a multiplication method that returns me a multiplication of 2 ten times, and I save the result in the list, and when my main method calls the multiplication, the control is repeated ten times through the loop and the result of the result in the list. This is without using a return return. Suppose that if I want to do this with a return on profitability, it looks like
public static IEnumerable Multiplication (int number, int times)
{ int result = number; for(int i=1;i<=times;i++) { result=number*i; yield return result; } }
static void Main (string [] args)
{ foreach(int i in Multiplication(2,10)) { Console.WriteLine(i); } Console.ReadKey(); }
Now there are small changes in the multiplication method, the return type is IEnumerable, and there is no other storage list because to work with the return type, the return value must be IEnumerable or IEnumerator, and since Yield provides stateful iteration, we don’t need an additional storage class result. So, in the above example, when the multiplication method is called from the Main method, it calculates the result for the 1st iteration and returns the result to the main method and returns to the loop and calculate the result for the 2nd iteration and return the result to the main method. Thus, the return returns to the method call one by one in each iteration. There is another keyword gap used in conjunction with Yield that causes the iteration to stop. For example, in the above example, if I want to calculate the multiplication only half the number of times (10/2 = 5), then the method looks like this:
public static IEnumerable Multiplication (int number, int times)
{ int result = number; for(int i=1;i<=times;i++) { result=number*i; yield return result; if (i == times / 2) yield break; } }
This method will now lead to multiplication in 2, 5 times. Hope this helps you understand the concept of profitability. For more, please visit http://msdn.microsoft.com/en-us/library/9k7k7cf0.aspx