Sohan's Blog

Living the Developer's Life

C# Keyword 'Yield Return' - I Find It Interesting

I have been using yield return in some of my codes and would like to share its interesting aspects. The following code example shows one dummy use of ‘yield return’-


public class YieldExample
{

public void Run()
{
IEnumerator numbers = getNumbers().GetEnumerator();
while (numbers.MoveNext())
{
Console.Write("x{0} ", numbers.Current);
}
}

private IEnumerable getNumbers()
{
for (int i = 0; i <>

Now, a code like new YieldExample().Run() would produce a output similar to this -
 "x0 y0 x1 y1 x2 y2 x3 y3 x4 y4 x5 y5 x6 y6 x7 y7 x8 y8 x9 y9"  
This output is certainly a little unusual but this is what ‘yield return’ is used for.

In a line, whenever you place a yield return statement, the control goes back to its caller. However, on the next call, program execution starts from the line immediate to the ‘yield return’ line. This can be used to avoid initializing/memorizing a collection of data if it makes sense to use them one after another and requires to move to control back and forth the iterator.