Yield statements are new to C# 2.0. It largely resembles python’s yield.
Its used to iterate through a set of results returned by a method, but the biggest difference being that the yield statements can maintain the state of that method.
It may be a bit confusing, yet pretty simple. Take a look at the following snippet.
Say, if you wanna print numbers between 0 and 50. What will you do ??
for(int i = 1; i < 50 ; i++)
{
Console.Write(i); //Just prints i in the screen
}
Really a child’s play. Now if you wanna return the intermediary values to the caller, then ??
Yield assists you in this scenario. Here is how you can do it.
private IEnumerable<int> GetNumbersBetween(int theStart, int theEnd) //Returns an IEnumerable<int> object that allows iteration using foreach
{
theStart++;
while(theStart < theEnd)
{
yield return theStart; //statement that returns the intermediary values
}
}
In the main method, you can use,
foreach(integer aNumber in GetNumbersBetween(0, 50)) //iteration is possible because GetNumbersBetween returns IEnumerable<int>
{
Console.Write(aNumber); //prints the number
}
You might wonder how the above snippet works. Lets dive in to it.
First iteration – Here GetNumbersBetween(1,50) will be executed. Unlike the ordinary methods, the GetNumbersBetween() won’t execute / exhaust the entire while loop. As there is a yield statement, it returns 1
Second iteration – Again the GetNumbersBetween(1, 50) will be called. Now since the method returns a yield value, it remembers the previous state. Now internally the value of theStart will be 2. So it returns 2 this time
Third iteration – Again the same method will be called, as usual, the value of theStart will be 3. So it returns 3 this time. This goes until theStart+1 = theEnd
This is how it works. Another confusing snippet for you. If you feel really bad, skip it.
while(true)
{
yield return 1; //Not an infinite loop
}
The above is not an infinite loop as this loop is totally controlled by the caller’s loop.
Things that you need to take care while using yield statements
- Yield can appear only inside a loop (obvious !!) — Check the comments to know more on this
- Parameters cannot be ref or out
- Don’t use yield inside catch or finally blocks (can’t think of a sample problem that covers this scenario)
