Monthly Archives: October 2006

Yield

I have always been somewhat envious of people that are able to blog about code. I’ve never felt that I am able to do so because I just don’t have any interesting code to talk about or any insight to provide. So it sort of hit home when Scoble and others talked about there being more talkers than doers. Am I just a ‘talker’ who happens to code for his day job? I was thinking of posting a bit of a batch script that parsed an XML file (that my previous manager still owes me lunch for–yes, that was a not-so-subtle reminder), but figured not many people cared about scripting–much less batch scripting (although I still might post it one day).

Tangent: It’s funny how your coding practices are gleaned from those that you work with (well, duh, I guess that makes sense). I’m pretty religious about using using, no thanks to David’s code reviews while in Messenger: Start using using today!.

Anyway, this morning I was helping debug some code of an architect on my team (there are plenty of them), when I saw a construct in C# I had never seen before: yield. I don’t really use iterators often/at all, and have never implemented one. It was explained to me that yield is useful for iterating over complex collections as you don’t need to keep state about where you were in a particular collection (especially if what you’re iterating over isn’t what appears to be a single collection, but multiple collections).

I’m not going to describe how yield works–a good amount of material is online. There’s a good intro in the first part of this article: C#: Create Elegant Code With Anonymous Methods, Iterators, And Partial Classes. It talks about the challenges of creating iterators without yield, and how the compiler implements yield. Also see Iterators, Not Just for Iteration. The idea of using continuations is pretty powerful–with this construct you can now write code that is more easily understood and maintained–a function will now look like it has a logical flow even though it will perform differently depending on the number of times it has been called. (This also makes it a little more annoying to step through while debugging.) CCR takes asynchronous programming to a whole new level using yield and anonymous delegates.

I haven’t played with yield, but I think I understand its usefulness. (I’m still not certain what yield break; accomplishes over a plain old break; or even just a return;. It seems to me that with yield the meanings of return and break are somewhat switched. Someone please enlighten me.)

Fun stuff. I suppose if I was a ‘doer’ I would have known about this earlier. Just like nullable types. It’s funny how you learn things from people you work with. All the more reason you need to surround with people you can actually learn from.