Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can someone demystify the yield keyword?

I have seen the yield keyword being used quite a lot on Stack Overflow and blogs. I don't use LINQ. Can someone explain the yield keyword?

I know that similar questions exist. But none really explain what is its use in plain simple language.

like image 720
Sandbox Avatar asked Aug 25 '09 19:08

Sandbox


People also ask

What is the yield keyword used for?

The yield keyword is use to do custom stateful iteration over a collection. The yield keyword tells the compiler that the method in which it appears is an iterator block. yield return <expression>; yield break; The yield return statement returns one element at a time.

Can you tell me what yield keyword does in C #?

The yield keyword performs custom and stateful iteration and returns each element of a collection one at a time sans the need of creating temporary collections. The yield keyword, first introduced in C# 2.0, T returns an object that implements the IEnumerable interface.

How does yield return work?

In the iterator block, the yield keyword is used together with the return keyword to provide a value to the enumerator object. This is the value that is returned, for example, in each loop of a foreach statement. The yield keyword is also used with break to signal the end of iteration."

Does LINQ use yield?

It's more the other way around, that linq is functional in style, so it uses yield.


1 Answers

By far the best explanation of this (that I've seen) is Jon Skeet's book - and that chapter is free! Chapter 6, C# in Depth. There is nothing I can add here that isn't covered.

Then buy the book; you will be a better C# programmer for it.


Q: Why didn't I write a longer answer here (paraphrased from comments); simple. As Eric Lippert observes (here), the yield construct (and the magic that goes behind it) is the single most complex bit of code in the C# compiler, and to try and describe it in a brief reply here is naïve at best. There are so many nuances to yield that IMO it is better to refer to a pre-existing (and fully qualified) resource.

Eric's blog now has 7 entries (and that is just the recent ones) discussing yield. I have a vast amount of respect for Eric, but his blog is probably more appropriate as a "further information" for people who are comfortable with the subject (yield in this case), as it typically describes a lot of the background design considerations. Best done in the context of a reasonable foundation.

(and yes, chapter 6 does download; I verified...)

like image 115
Marc Gravell Avatar answered Oct 19 '22 13:10

Marc Gravell