Wednesday, June 30, 2010

Yeild

One interesting new feature of the C# 2.0 is the "yield" keyword.  Basically it is used to iterate through objects returned by a method. It creates a state engine in IL so you can create methods that retain their state and dont have to go through the pain of maintaining state in your code.

Here is a simple example that demonstrates how yield return can be used to maintain state in a method. Every time you call  GetInt() you will receive a new incremented integer.
public static IEnumerable GetInt()
{
   for (int i = 0; i < 5; i++)
       yield return i;
}


Here's the implementation.

public partial class Yield : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        foreach (int i in GetInt())
            Response.Write(i.ToString());
    }

    public static IEnumerable GetInt()
    {
          for (int i = 0; i < 5; i++)
            yield return i;
    }
}
Here  is the difference  on the execution

Typical Implementation                                  Yield Implementation 


Caller calls function                                            Caller calls function
Function executes and returns list                       Caller requests item
Caller uses list                                                    Next item returned
                                                                          Goto step #2


Although the execution of the yield implementation is a little more complicated, what we end up with is an implementation that "pulls" items one at a time instead of having to build an entire list before returning to the client.


Usually, the "yield" keyword will be useful when you implement the GetEnumerator() method of the IEnumerable interface
After all the Yield is creating addional overhead and use when required exactly.

0 comments:

Post a Comment