Monthly Archives: September 2018

The ‘yield’ keyword

The ‘yield’ keyword is something that I’ve just ignored for years and even though I had an idea of what it was doing i’ve actually never used it myself.

This is what msdn has to say:

When you use the yield keyword in a statement, you indicate that the method, operator, or get accessor in which it appears is an iterator. Using yield to define an iterator removes the need for an explicit extra class (the class that holds the state for an enumeration, see IEnumerator<T> for an example) when you implement the IEnumerable and IEnumerator pattern for a custom collection type.

Alright, all clear?

So basiclly you are able to return an IEnumerable to use in say a for each. I guess it hasn’t that many uses, but one use is to batch a list so I came up with a great extension method for batching lists.

 

Now look at that beauty 🙂

So it returns <count> number of elements every iteration.

My test code was the following

and the output of this is as follows

So every iteration it returns 3 elements except the last iteration where it returns 1 element.

Now, it’s not the most used scenario, but definitely something to have i you library when needed.