views:

235

answers:

1

I've traditionally used yield in C# without the return, e.g.:

IEnumerable<T> Foobar() {
   foreach( var foo in _stuff ) {
      yield foo;
   }
}

But in other examples I've seen it written as "yield return foo;", see: http://msdn.microsoft.com/en-us/library/9k7k7cf0%28VS.80%29.aspx.

Is there any difference?

+4  A: 

C# does not allow yield all by itself - only yield return and yield break.

yield is a contextual keyword that is only recognized inside iterator blocks and only in conjunction with either return or break.

Andrew Hare
Thanks. Not sure why I remembered being able to write yield without return. Too long away from C# I guess.
Alex Black
In the original design of iterator blocks it was just yield without the return, but I don't believe any of those versions ever actually shipped to the public. The design team realized that if they made it yield return then they would not have to make a new reserved keyword.
Eric Lippert