Codelog

foreach(Snippet aSnippet in CodeLog){ aSnippet.GetSolution(); }

Yield statements in C#

with 2 comments

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)

Written by sudarsanyes

November 3rd, 2008 at 10:12 am

2 Responses to 'Yield statements in C#'

Subscribe to comments with RSS or TrackBack to 'Yield statements in C#'.

  1. yield can only be used inside a loop?
    Can’t I have a straight execution of statements which can yield an intermediary value and then return back to the place and continue and then finally return the final value?

    def foo():
      print “before yield”
      yield 1234
      print “after yield”
      return 9876

    Can’t you do something like this?

    cnu

    4 Nov 08 at 12:09 am

  2. Yeah. It is possible, but the method Foo() will not be executed unless it is iterated (it should be returning an enumerable object in case of C#).

    i.e.,
    foreach(int i in foo())
    {
        Console.Write(i); //will print i
    }

    The net output will be,

    before yield
    1234
    after yield
    9876

    Where as,

    private void Bar()
    {
        foo(); //will not do anything
    }

    sudarsanyes

    4 Nov 08 at 7:57 am

Leave a Reply