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
{
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
{
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