The yield keyword

Here is a keyword I think is underused, probably because it is specific to .NET and thus developers coming from other languages don’t have the reflex to use it. The yield keyword allows you to return a collection from a method without having to declare it nor add the elements that compose it. Intriguing isn’t it ? Let’s see an example to understand this. Imagine I create a method that calculates surfaces based on two even-sized collections received as parameters (Figure 1).

yield-normal-method

Figure 1

So now you can see the declaration of the collection to return, the addition of elements to this collection inside the loop and the return statement at the end of the method. Let’s now see how this same method can be coded by using the yield keyword (Figure 2).

yield

Figure 2

You can directly figure out that the collection declaration is gone, as long as the addition of elements to it of course. Finally, the return instruction is now inside the loop and preceded by the yield keyword. And instead of returning a collection, we directly return the element that was previously added to the collection. The call to this method doesn’t change at all though. I then call it to get all the values and display them in the console (Figure 3).

yield-call

Figure 3

I can finally execute the application and check that the result is the one I expected (Figure 4).

yield-result

Figure 4

Note, however, that this technique can only be applied with an iterator that returns IEnumerable, IEnumerator or one of their generic version.

Advertisements