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.
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.
yield
is not directly related to LINQ, but rather to iterator blocks. The linked MSDN article gives great detail on this language feature. See especially the Using Iterators section. For deep details of iterator blocks, see Eric Lippert's recent blog posts on the feature. For the general concept, see the Wikipedia article on iterators.The
yield
keyword is used with methods that returnIEnumerable<T>
orIEnumerator<T>
and it makes the compiler generate a class that implements the necessary plumbing for using the iterator. E.g.Given the above the compiler will generate a class that implements
IEnumerator<int>
,IEnumerable<int>
andIDisposable
(actually it will also implement the non-generic versions ofIEnumerable
andIEnumerator
).This allows you to call the method
SequenceOfOneToThree
in aforeach
loop like thisAn iterator is a state machine, so each time
yield
is called the position in the method is recorded. If the iterator is moved to the next element, the method resumes right after this position. So the first iteration returns 1 and marks that position. The next iterator resumes right after one and thus returns 2 and so forth.Needless to say you can generate the sequence in any way you like, so you don't have to hard code the numbers like I did. Also, if you want to break the loop you can use
yield break
.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 toyield
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...)