Monday, May 9, 2011

yield vs return in C#

The yield keyword signals to the compiler that the method in which it appears is an iterator block.

  • yield can be used to return partially.
  • yield maintains the state of the object
Simple example

void Main()
{
foreach(int i in GetDivideByTwo())
{
Console.WriteLine(i);
}
}


static System.Collections.Generic.IEnumerable GetDivideByTwo()
{
for (int i = 0; i < 100; i++)
yield return i/2;
}


Here is couple of good links

http://stackoverflow.com/questions/410026/c-proper-use-of-yield-return

http://stackoverflow.com/questions/1088442/what-is-the-purpose-advantage-of-using-yield-return-iterators-in-c/1088452#1088452

http://stackoverflow.com/questions/3969963/when-not-to-use-yield-return/3970171#3970171



No comments:

Post a Comment