Monday, February 20, 2012

How to use the Yield statement in C#

The Yield is  a very interesting statement. You use it with the Return statement to build a collection.



// Step through the list until we get to the '10' 
void DoSomethingToTheNumbers()
{
foreach (int num in MakeListofNumbers())
{
if (num == 10) return;
}
}


// makes an IEnumerable list of '3', '4'.. 19
IEnumerable MakeListofNumbers()
{
for(int i = 3; i < 20; i++)
{
yield return i;
}
}


 In the method MakeListofNumbers() an IEnumerable of integer values is created. This is built up in a "lazy" manner.

So in the DoSomethingToTheNumbers() method, we can enumerate the MakeListofNumbers() by using a foreach statement. That is we can step through each element in the IEnumerable list.

To see how neat this is it is best to step through it using the debugger. As you step through the foreach statement, the code will magically jump down into the MakeListofNumbers() function and generate the next number in the list.

(To Computer Science nerds this is called a "Continuation")

Why is it called Yield? I think it's because the method yields control to the calling function.

Is it useful?
Well yes but not often. This is really handy if the enumeration generation method is doing something rather computationally expensive. If it is, and if you want to cease the foreach partway through, that is, you want to foreach only the first n elements in the IEnumerable, then you can and you will not have wasted time creating the entire IEnumerable list.


No comments:

Post a Comment