Bob's Blog
Random neural firings: life in general and life as a programmer
C# enumerator and "yield return"

My first impression of the new C# "yield return" feature for implementing IEnumerable<T> was that it's syntax candy, and not too useful.  Probably I got this impression because the first time I tried to introduce it into my code I was working with a class that already implemented the IEnumerator interface, so I was working with a class in which I had already implemented all the state necessary to return to processing on the next call to MoveNext() method.

Anyhow, I've changed my mind.  The power of the "yield return" feature becomes obvious when you haven't yet converted a processing loop into an Enumerator.  This is particularly true if there is some annoying boiler-plate looping that has been copied-and-pasted into various methods.  You'd like to remove the common code, but certain method-specific processing is interleaved within the loop.

The "yield return" method gives you a way to code your loop in one place.  Essentially, create a method that returns IEnumerable<T> by replacing the method-specific code with "yield return".   In the original code, replace the loop with

  foreach (T foo in MyNewEnumable)
  {
      // method specific bit

Before trying anything complicated with the "yield return" syntax, it's a good idea to walk thru a trivial case in the debugger. 

2006-07-26 12:21:21 GMT
Add to My Yahoo! RSS