yield foreach

A while ago I submitted a suggestion to MS Connect: yield return to also yield collections. yield foreach could be a way to yield return items one by one without explicitly writing yield return in a foreach loop. This would basically be a way to flatten nested iterators like does. On the feedback page I also give an example, where this might be useful.

It turns out, the C# team has already been thinking about adding this feature in some future version (post-Orcas). Wes Dyer from the C# Compiler Team has an excellent post about this feature here.

An interesting question is: why is the foreach keyword there? Wouldn't it be sufficient to just write yield return MyCollection; and that's it? The compiler would be able to figure out if the thing implements IEnumerable, right? Well, consider what happens if the return type of the main (outer) iterator is IEnumerable<IEnumerable>? In this case the compiler wouldn't know what to do - just return the collection as if it would be an item or flatten the collection? yield foreach is a way to explicitly tell the compiler: yes, I'm sure, please emit the foreach loop for me.
Another advantage is that no new keyword has to be introduced - both yield and foreach are already reserved keywords.

For those interested, Wes links to a research paper about iterators: Iterators revisited: proof rules and implementation


nikov said...

Hi, Kirill.
Just to be completely correct: in fact, 'yield' is not a keyword in C#.

Kirill Osenkov said...

Thanks, Vladimir!

You're right, 'yield' is a contextual keyword.