<p>In the <a href="https://stackoverflow.com/questions/39447/how-can-i-expose-only-a-fragment-of-ilist">How Can I Expose Only a Fragment of IList&lt;></a> question one of the answers had the following code snippet:</p>

<pre><code>IEnumerable&lt;object&gt; FilteredList()
{
    foreach(object item in FullList)
    {
        if(IsItemInPartialList(item))
            yield return item;
    }
}
</code></pre>

<p>What does the yield keyword do there?  I've seen it referenced in a couple places, and one other question, but I haven't quite figured out what it actually does.  I'm used to thinking of yield in the sense of one thread yielding to another, but that doesn't seem relevant here.</p>

[{'answer_id': 39482, 'author': 'Joel Coehoorn', 'author_id': 3043, 'author_profile': 'https://Stackoverflow.com/users/3043', 'pm_score': 9, 'selected': False, 'text': '<p>Iteration.  It creates a state machine "under the covers" that remembers where you were on each additional cycle of the function and picks up from there.</p>\n'}, {'answer_id': 39483, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 4, 'selected': False, 'text': "<p>It is a very simple and easy way to create an enumerable for your object.  The compiler creates a class that wraps your method and that implements, in this case, IEnumerable&lt;object>.  Without the yield keyword, you'd have to create an object that implements IEnumerable&lt;object>.</p>\n"}, {'answer_id': 39486, 'author': 'aku', 'author_id': 1196, 'author_profile': 'https://Stackoverflow.com/users/1196', 'pm_score': 3, 'selected': False, 'text': "<p>It's producing enumerable sequence. What it does is actually creating local IEnumerable sequence and returning it as a method result</p>\n"}, {'answer_id': 39488, 'author': 'Konrad Rudolph', 'author_id': 1968, 'author_profile': 'https://Stackoverflow.com/users/1968', 'pm_score': 5, 'selected': False, 'text': '<p>Intuitively, the keyword returns a value from the function without leaving it, i.e. in your code example it returns the current <code>item</code> value and then resumes the loop. More formally, it is used by the compiler to generate code for an <em>iterator</em>. Iterators are functions that return <code>IEnumerable</code> objects. The <a href="http://msdn.microsoft.com/en-us/library/65zzykke%28VS.80%29.aspx" rel="noreferrer">MSDN</a> has several <a href="http://msdn.microsoft.com/en-us/magazine/cc163970.aspx" rel="noreferrer">articles</a> about them.</p>\n'}, {'answer_id': 39496, 'author': 'Mendelt', 'author_id': 3320, 'author_profile': 'https://Stackoverflow.com/users/3320', 'pm_score': 11, 'selected': True, 'text': "<p>The <code>yield</code> contextual keyword actually does quite a lot here.</p>\n<p>The function returns an object that implements the <code>IEnumerable&lt;object&gt;</code> interface. If a calling function starts <code>foreach</code>ing over this object, the function is called again until it &quot;yields&quot;. This is syntactic sugar introduced in <strong>C# 2.0</strong>. In earlier versions you had to create your own <code>IEnumerable</code> and <code>IEnumerator</code> objects to do stuff like this.</p>\n<p>The easiest way understand code like this is to type-in an example, set some breakpoints and see what happens. Try stepping through this example:</p>\n<pre><code>public void Consumer()\n{\n    foreach(int i in Integers())\n    {\n        Console.WriteLine(i.ToString());\n    }\n}\n\npublic IEnumerable&lt;int&gt; Integers()\n{\n    yield return 1;\n    yield return 2;\n    yield return 4;\n    yield return 8;\n    yield return 16;\n    yield return 16777216;\n}\n</code></pre>\n<p>When you step through the example, you'll find the first call to <code>Integers()</code> returns <code>1</code>. The second call returns <code>2</code> and the line <code>yield return 1</code> is not executed again.</p>\n<p>Here is a real-life example:</p>\n<pre><code>public IEnumerable&lt;T&gt; Read&lt;T&gt;(string sql, Func&lt;IDataReader, T&gt; make, params object[] parms)\n{\n    using (var connection = CreateConnection())\n    {\n        using (var command = CreateCommand(CommandType.Text, sql, connection, parms))\n        {\n            command.CommandTimeout = dataBaseSettings.ReadCommandTimeout;\n            using (var reader = command.ExecuteReader())\n            {\n                while (reader.Read())\n                {\n                    yield return make(reader);\n                }\n            }\n        }\n    }\n}\n</code></pre>\n"}, {'answer_id': 39507, 'author': 'Svend', 'author_id': 2491, 'author_profile': 'https://Stackoverflow.com/users/2491', 'pm_score': 7, 'selected': False, 'text': '<p>Recently Raymond Chen also ran an interesting series of articles on the yield keyword.</p>\n\n<ul>\n<li><a href="https://devblogs.microsoft.com/oldnewthing/20080812-00/?p=21273" rel="noreferrer">The implementation of iterators in C# and its consequences (part 1)</a></li>\n<li><a href="https://devblogs.microsoft.com/oldnewthing/20080813-00/?p=21253" rel="noreferrer">The implementation of iterators in C# and its consequences (part 2)</a></li>\n<li><a href="https://devblogs.microsoft.com/oldnewthing/20080814-00/?p=21243" rel="noreferrer">The implementation of iterators in C# and its consequences (part 3)</a></li>\n<li><a href="https://devblogs.microsoft.com/oldnewthing/20080815-00/?p=21223" rel="noreferrer">The implementation of iterators in C# and its consequences (part 4)</a></li>\n</ul>\n\n<p>While it\'s nominally used for easily implementing an iterator pattern, but can be generalized into a state machine. No point in quoting Raymond, the last part also links to other uses (but the example in Entin\'s blog is esp good, showing how to write async safe code).</p>\n'}, {'answer_id': 39600, 'author': 'Gishu', 'author_id': 1695, 'author_profile': 'https://Stackoverflow.com/users/1695', 'pm_score': -1, 'selected': False, 'text': "<p>It's trying to bring in some Ruby Goodness :)<br>\n<strong>Concept:</strong> This is some sample Ruby Code that prints out each element of the array   </p>\n\n<pre><code> rubyArray = [1,2,3,4,5,6,7,8,9,10]\n    rubyArray.each{|x| \n        puts x   # do whatever with x\n    }\n</code></pre>\n\n<p>The Array's each method implementation <strong>yields</strong> control over to the caller (the 'puts x') with <strong>each</strong> element of the array neatly presented as x. The caller can then do whatever it needs to do with x.</p>\n\n<p>However <strong>.Net</strong> doesn't go all the way here.. C# seems to have coupled yield with IEnumerable, in a way forcing you to write a foreach loop in the caller as seen in Mendelt's response. Little less elegant.</p>\n\n<pre><code>//calling code\nforeach(int i in obCustomClass.Each())\n{\n    Console.WriteLine(i.ToString());\n}\n\n// CustomClass implementation\nprivate int[] data = {1,2,3,4,5,6,7,8,9,10};\npublic IEnumerable&lt;int&gt; Each()\n{\n   for(int iLooper=0; iLooper&lt;data.Length; ++iLooper)\n        yield return data[iLooper]; \n}\n</code></pre>\n"}, {'answer_id': 14328230, 'author': 'BoiseBaked', 'author_id': 1978711, 'author_profile': 'https://Stackoverflow.com/users/1978711', 'pm_score': 4, 'selected': False, 'text': "<p>The C# yield keyword, to put it simply, allows many calls to a body of code, referred to as an iterator, that knows how to return before it's done and, when called again, continues where it left off - i.e. it helps an iterator become transparently stateful per each item in a sequence that the iterator returns in successive calls.</p>\n\n<p>In JavaScript, the same concept is called Generators.</p>\n"}, {'answer_id': 15977474, 'author': 'Shivprasad Koirala', 'author_id': 993672, 'author_profile': 'https://Stackoverflow.com/users/993672', 'pm_score': 8, 'selected': False, 'text': '<p>Yield has two great uses,</p>\n\n<ol>\n<li><p>It helps to provide custom iteration without creating temp collections.</p></li>\n<li><p>It helps to do stateful iteration.\n<a href="https://i.stack.imgur.com/Sza04.png" rel="noreferrer"><img src="https://i.stack.imgur.com/Sza04.png" alt="enter image description here"></a></p></li>\n</ol>\n\n<p>In order to explain above two points more demonstratively, I have created a simple video  you can watch it <a href="http://www.youtube.com/watch?v=4fju3xcm21M" rel="noreferrer">here</a></p>\n'}, {'answer_id': 22021424, 'author': 'RKS', 'author_id': 1733852, 'author_profile': 'https://Stackoverflow.com/users/1733852', 'pm_score': 6, 'selected': False, 'text': '<p><code>yield return</code> is used with enumerators. On each call of yield statement, control is returned to the caller but it ensures that the callee\'s state is maintained. Due to this, when the caller enumerates the next element, it continues execution in the callee method from statement immediately after the <code>yield</code> statement.</p>\n\n<p>Let us try to understand this with an example. In this example, corresponding to each line I have mentioned the order in which execution flows.</p>\n\n<pre><code>static void Main(string[] args)\n{\n    foreach (int fib in Fibs(6))//1, 5\n    {\n        Console.WriteLine(fib + " ");//4, 10\n    }            \n}\n\nstatic IEnumerable&lt;int&gt; Fibs(int fibCount)\n{\n    for (int i = 0, prevFib = 0, currFib = 1; i &lt; fibCount; i++)//2\n    {\n        yield return prevFib;//3, 9\n        int newFib = prevFib + currFib;//6\n        prevFib = currFib;//7\n        currFib = newFib;//8\n    }\n}\n</code></pre>\n\n<p>Also, the state is maintained for each enumeration. Suppose, I have another call to <code>Fibs()</code> method then the state will be reset for it.</p>\n'}, {'answer_id': 28000413, 'author': 'Marquinho Peli', 'author_id': 2992192, 'author_profile': 'https://Stackoverflow.com/users/2992192', 'pm_score': 7, 'selected': False, 'text': "<p>At first sight, yield return is a <strong>.NET</strong> sugar to return an <strong>IEnumerable</strong>.</p>\n\n<p>Without yield, all the items of the collection are created at once:</p>\n\n<pre><code>class SomeData\n{\n    public SomeData() { }\n\n    static public IEnumerable&lt;SomeData&gt; CreateSomeDatas()\n    {\n        return new List&lt;SomeData&gt; {\n            new SomeData(), \n            new SomeData(), \n            new SomeData()\n        };\n    }\n}\n</code></pre>\n\n<p>Same code using yield, it returns item by item:</p>\n\n<pre><code>class SomeData\n{\n    public SomeData() { }\n\n    static public IEnumerable&lt;SomeData&gt; CreateSomeDatas()\n    {\n        yield return new SomeData();\n        yield return new SomeData();\n        yield return new SomeData();\n    }\n}\n</code></pre>\n\n<p>The advantage of using yield is that if the function consuming your data simply needs the first item of the collection, the rest of the items won't be created. </p>\n\n<p>The yield operator allows the creation of items as it is demanded. That's a good reason to use it.</p>\n"}, {'answer_id': 34096356, 'author': 'Strydom', 'author_id': 5632496, 'author_profile': 'https://Stackoverflow.com/users/5632496', 'pm_score': 6, 'selected': False, 'text': '<p>A list or array implementation loads all of the items immediately whereas the yield implementation provides a deferred execution solution.</p>\n\n<p>In practice, it is often desirable to perform the minimum amount of work as needed in order to reduce the resource consumption of an application.</p>\n\n<p>For example, we may have an application that process millions of records from a database. The following benefits can be achieved when we use IEnumerable in a deferred execution pull-based model:</p>\n\n<ul>\n<li><b>Scalability, reliability and predictability</b> are likely to improve since the number of records does not significantly affect the application’s resource requirements.</li>\n<li><b>Performance and responsiveness</b> are likely to improve since processing can start immediately instead of waiting for the entire collection to be loaded first.</li>\n<li><b>Recoverability and utilisation</b> are likely to improve since the application can be stopped, started, interrupted or fail. Only the items in progress will be lost compared to pre-fetching all of the data where only using a portion of the results was actually used.</li>\n<li><b>Continuous processing</b> is possible in environments where constant workload streams are added.</li>\n</ul>\n\n<p>Here is a comparison between build a collection first such as a list compared to using yield.</p>\n\n<p><strong>List Example</strong></p>\n\n<pre><code>    public class ContactListStore : IStore&lt;ContactModel&gt;\n    {\n        public IEnumerable&lt;ContactModel&gt; GetEnumerator()\n        {\n            var contacts = new List&lt;ContactModel&gt;();\n            Console.WriteLine("ContactListStore: Creating contact 1");\n            contacts.Add(new ContactModel() { FirstName = "Bob", LastName = "Blue" });\n            Console.WriteLine("ContactListStore: Creating contact 2");\n            contacts.Add(new ContactModel() { FirstName = "Jim", LastName = "Green" });\n            Console.WriteLine("ContactListStore: Creating contact 3");\n            contacts.Add(new ContactModel() { FirstName = "Susan", LastName = "Orange" });\n            return contacts;\n        }\n    }\n\n    static void Main(string[] args)\n    {\n        var store = new ContactListStore();\n        var contacts = store.GetEnumerator();\n\n        Console.WriteLine("Ready to iterate through the collection.");\n        Console.ReadLine();\n    }\n</code></pre>\n\n<p><strong><em>Console Output</em></strong>\n<br />\nContactListStore: Creating contact 1\n<br />\nContactListStore: Creating contact 2\n<br />\nContactListStore: Creating contact 3\n<br />\nReady to iterate through the collection.</p>\n\n<p>Note: The entire collection was loaded into memory without even asking for a single item in the list</p>\n\n<p><strong>Yield Example</strong></p>\n\n<pre><code>public class ContactYieldStore : IStore&lt;ContactModel&gt;\n{\n    public IEnumerable&lt;ContactModel&gt; GetEnumerator()\n    {\n        Console.WriteLine("ContactYieldStore: Creating contact 1");\n        yield return new ContactModel() { FirstName = "Bob", LastName = "Blue" };\n        Console.WriteLine("ContactYieldStore: Creating contact 2");\n        yield return new ContactModel() { FirstName = "Jim", LastName = "Green" };\n        Console.WriteLine("ContactYieldStore: Creating contact 3");\n        yield return new ContactModel() { FirstName = "Susan", LastName = "Orange" };\n    }\n}\n\nstatic void Main(string[] args)\n{\n    var store = new ContactYieldStore();\n    var contacts = store.GetEnumerator();\n\n    Console.WriteLine("Ready to iterate through the collection.");\n    Console.ReadLine();\n}\n</code></pre>\n\n<p><strong><em>Console Output</em></strong>\n<br />\nReady to iterate through the collection.</p>\n\n<p>Note: The collection wasn\'t executed at all. This is due to the "deferred execution" nature of IEnumerable. Constructing an item will only occur when it is really required.</p>\n\n<p>Let\'s call the collection again and obverse the behaviour when we fetch the first contact in the collection.</p>\n\n<pre><code>static void Main(string[] args)\n{\n    var store = new ContactYieldStore();\n    var contacts = store.GetEnumerator();\n    Console.WriteLine("Ready to iterate through the collection");\n    Console.WriteLine("Hello {0}", contacts.First().FirstName);\n    Console.ReadLine();\n}\n</code></pre>\n\n<p><strong><em>Console Output</em></strong>\n<br />\nReady to iterate through the collection\n<br />\nContactYieldStore: Creating contact 1\n<br />\nHello Bob</p>\n\n<p>Nice! Only the first contact was constructed when the client "pulled" the item out of the collection.</p>\n'}, {'answer_id': 36962062, 'author': 'barlop', 'author_id': 385907, 'author_profile': 'https://Stackoverflow.com/users/385907', 'pm_score': 3, 'selected': False, 'text': '<p>This <a href="http://www.dotnetperls.com/yield" rel="noreferrer">link</a> has a simple example </p>\n\n<p>Even simpler examples are here</p>\n\n<pre><code>public static IEnumerable&lt;int&gt; testYieldb()\n{\n    for(int i=0;i&lt;3;i++) yield return 4;\n}\n</code></pre>\n\n<p>Notice that yield return won\'t return from the method. You can even put a <code>WriteLine</code> after the <code>yield return</code></p>\n\n<p>The above produces an IEnumerable of 4 ints 4,4,4,4</p>\n\n<p>Here with a <code>WriteLine</code>.  Will add 4 to the list, print abc, then add 4 to the list, then complete the method and so really return from the method(once the method has completed, as would happen with a procedure without a return). But this would have a value, an <code>IEnumerable</code> list of <code>int</code>s, that it returns on completion.</p>\n\n<pre><code>public static IEnumerable&lt;int&gt; testYieldb()\n{\n    yield return 4;\n    console.WriteLine("abc");\n    yield return 4;\n}\n</code></pre>\n\n<p>Notice also that when you use yield, what you are returning is not of the same type as the function. It\'s of the type of an element within the <code>IEnumerable</code> list.</p>\n\n<p>You use yield with the method\'s return type as <code>IEnumerable</code>. If the method\'s return type is <code>int</code> or <code>List&lt;int&gt;</code> and you use <code>yield</code>, then it won\'t compile. You can use <code>IEnumerable</code> method return type without yield but it seems maybe you can\'t use yield without <code>IEnumerable</code> method return type.</p>\n\n<p>And to get it to execute you have to call it in a special way.  </p>\n\n<pre><code>static void Main(string[] args)\n{\n    testA();\n    Console.Write("try again. the above won\'t execute any of the function!\\n");\n\n    foreach (var x in testA()) { }\n\n\n    Console.ReadLine();\n}\n\n\n\n// static List&lt;int&gt; testA()\nstatic IEnumerable&lt;int&gt; testA()\n{\n    Console.WriteLine("asdfa");\n    yield return 1;\n    Console.WriteLine("asdf");\n}\n</code></pre>\n'}, {'answer_id': 39273209, 'author': 'kmote', 'author_id': 93394, 'author_profile': 'https://Stackoverflow.com/users/93394', 'pm_score': 5, 'selected': False, 'text': '<p>Here is a simple way to understand the concept:\nThe basic idea is, if you want a collection that you can use "<code>foreach</code>" on, but gathering the items into the collection is expensive for some reason (like querying them out of a database), AND you will often not need the entire collection, then you create a function that builds the collection one item at a time and yields it back to the consumer (who can then terminate the collection effort early).</p>\n\n<p><strong>Think of it this way:</strong> You go to the meat counter and want to buy a pound of sliced ham. The butcher takes a 10-pound ham to the back, puts it on the slicer machine, slices the whole thing, then brings the pile of slices back to you and measures out a pound of it. (OLD way).\nWith <code>yield</code>, the butcher brings the slicer machine to the counter, and starts slicing and "yielding" each slice onto the scale until it measures 1-pound, then wraps it for you and you\'re done. <em>The Old Way may be better for the butcher (lets him organize his machinery the way he likes), but the New Way is clearly more efficient in most cases for the consumer.</em></p>\n'}, {'answer_id': 44801657, 'author': 'Martin Liversage', 'author_id': 98607, 'author_profile': 'https://Stackoverflow.com/users/98607', 'pm_score': 5, 'selected': False, 'text': '<p>The <code>yield</code> keyword allows you to create an <code>IEnumerable&lt;T&gt;</code> in the form on an <a href="https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/iterators" rel="noreferrer"><em>iterator block</em></a>. This iterator block supports <em>deferred executing</em> and if you are not familiar with the concept it may appear almost magical. However, at the end of the day it is just code that executes without any weird tricks.</p>\n\n<p>An iterator block can be described as syntactic sugar where the compiler generates a state machine that keeps track of how far the enumeration of the enumerable has progressed. To enumerate an enumerable, you often use a <code>foreach</code> loop. However, a <code>foreach</code> loop is also syntactic sugar. So you are two abstractions removed from the real code which is why it initially might be hard to understand how it all works together.</p>\n\n<p>Assume that you have a very simple iterator block:</p>\n\n<pre><code>IEnumerable&lt;int&gt; IteratorBlock()\n{\n    Console.WriteLine("Begin");\n    yield return 1;\n    Console.WriteLine("After 1");\n    yield return 2;\n    Console.WriteLine("After 2");\n    yield return 42;\n    Console.WriteLine("End");\n}\n</code></pre>\n\n<p>Real iterator blocks often have conditions and loops but when you check the conditions and unroll the loops they still end up as <code>yield</code> statements interleaved with other code.</p>\n\n<p>To enumerate the iterator block a <code>foreach</code> loop is used:</p>\n\n<pre><code>foreach (var i in IteratorBlock())\n    Console.WriteLine(i);\n</code></pre>\n\n<p>Here is the output (no surprises here):</p>\n\n<pre>\nBegin\n1\nAfter 1\n2\nAfter 2\n42\nEnd\n</pre>\n\n<p>As stated above <code>foreach</code> is syntactic sugar:</p>\n\n<pre><code>IEnumerator&lt;int&gt; enumerator = null;\ntry\n{\n    enumerator = IteratorBlock().GetEnumerator();\n    while (enumerator.MoveNext())\n    {\n        var i = enumerator.Current;\n        Console.WriteLine(i);\n    }\n}\nfinally\n{\n    enumerator?.Dispose();\n}\n</code></pre>\n\n<p>In an attempt to untangle this I have crated a sequence diagram with the abstractions removed:</p>\n\n<p><a href="https://i.stack.imgur.com/81KNH.png" rel="noreferrer"><img src="https://i.stack.imgur.com/81KNH.png" alt="C# iterator block sequence diagram"></a></p>\n\n<p>The state machine generated by the compiler also implements the enumerator but to make the diagram more clear I have shown them as separate instances. (When the state machine is enumerated from another thread you do actually get separate instances but that detail is not important here.)</p>\n\n<p>Every time you call your iterator block a new instance of the state machine is created. However, none of your code in the iterator block is executed until <code>enumerator.MoveNext()</code> executes for the first time. This is how deferred executing works. Here is a (rather silly) example:</p>\n\n<pre><code>var evenNumbers = IteratorBlock().Where(i =&gt; i%2 == 0);\n</code></pre>\n\n<p>At this point the iterator has not executed. The <code>Where</code> clause creates a new <code>IEnumerable&lt;T&gt;</code> that wraps the <code>IEnumerable&lt;T&gt;</code> returned by <code>IteratorBlock</code> but this enumerable has yet to be enumerated. This happens when you execute a <code>foreach</code> loop:</p>\n\n<pre><code>foreach (var evenNumber in evenNumbers)\n    Console.WriteLine(eventNumber);\n</code></pre>\n\n<p>If you enumerate the enumerable twice then a new instance of the state machine is created each time and your iterator block will execute the same code twice.</p>\n\n<p>Notice that LINQ methods like <code>ToList()</code>, <code>ToArray()</code>, <code>First()</code>, <code>Count()</code> etc. will use a <code>foreach</code> loop to enumerate the enumerable. For instance <code>ToList()</code> will enumerate all elements of the enumerable and store them in a list. You can now access the list to get all elements of the enumerable without the iterator block executing again. There is a trade-off between using CPU to produce the elements of the enumerable multiple times and memory to store the elements of the enumeration to access them multiple times when using methods like <code>ToList()</code>.</p>\n'}, {'answer_id': 49847398, 'author': 'Casey Plummer', 'author_id': 704532, 'author_profile': 'https://Stackoverflow.com/users/704532', 'pm_score': 5, 'selected': False, 'text': "<p>If I understand this correctly, here's how I would phrase this from the perspective of the function implementing IEnumerable with yield.</p>\n\n<ul>\n<li>Here's one.</li>\n<li>Call again if you need another.</li>\n<li>I'll remember what I already gave you.</li>\n<li>I'll only know if I can give you another when you call again.</li>\n</ul>\n"}, {'answer_id': 58442021, 'author': 'maxspan', 'author_id': 2209468, 'author_profile': 'https://Stackoverflow.com/users/2209468', 'pm_score': 5, 'selected': False, 'text': '<p>One major point about Yield keyword is <strong>Lazy Execution</strong>. Now what I mean by Lazy Execution is to execute when needed. A better way to put it is by giving an example</p>\n<p><strong>Example: Not using Yield i.e. No Lazy Execution.</strong></p>\n<pre><code>public static IEnumerable&lt;int&gt; CreateCollectionWithList()\n{\n    var list =  new List&lt;int&gt;();\n    list.Add(10);\n    list.Add(0);\n    list.Add(1);\n    list.Add(2);\n    list.Add(20);\n\n    return list;\n}\n</code></pre>\n<p><strong>Example: using Yield i.e. Lazy Execution.</strong></p>\n<pre><code>public static IEnumerable&lt;int&gt; CreateCollectionWithYield()\n{\n    yield return 10;\n    for (int i = 0; i &lt; 3; i++) \n    {\n        yield return i;\n    }\n\n    yield return 20;\n}\n</code></pre>\n<p>Now when I call both methods.</p>\n<pre><code>var listItems = CreateCollectionWithList();\nvar yieldedItems = CreateCollectionWithYield();\n</code></pre>\n<p>you will notice listItems will have a 5 items inside it (hover your mouse on listItems while debugging).\nWhereas yieldItems will just have a reference to the method and not the items.\nThat means it has not executed the process of getting items inside the method. A very efficient way of getting data only when needed.\nActual implementation of yield can be seen in ORM like Entity Framework and NHibernate etc.</p>\n'}, {'answer_id': 69410126, 'author': 'Pascal Carmoni', 'author_id': 2101398, 'author_profile': 'https://Stackoverflow.com/users/2101398', 'pm_score': -1, 'selected': False, 'text': '<p>Simple demo to understand yield</p>\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nnamespace ConsoleApp_demo_yield {\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            var letters = new List&lt;string&gt;() { &quot;a1&quot;, &quot;b1&quot;, &quot;c2&quot;, &quot;d2&quot; };\n\n            // Not yield\n            var test1 = GetNotYield(letters);\n\n            foreach (var t in test1)\n            {\n                Console.WriteLine(t);\n            }\n\n            // yield\n            var test2 = GetWithYield(letters).ToList();\n\n            foreach (var t in test2)\n            {\n                Console.WriteLine(t);\n            }\n\n            Console.ReadKey();\n        }\n\n        private static IList&lt;string&gt; GetNotYield(IList&lt;string&gt; list)\n        {\n            var temp = new List&lt;string&gt;();\n            foreach(var x in list)\n            {\n                \n                if (x.Contains(&quot;2&quot;)) { \n                temp.Add(x);\n                }\n            }\n\n            return temp;\n        }\n\n        private static IEnumerable&lt;string&gt; GetWithYield(IList&lt;string&gt; list)\n        {\n            foreach (var x in list)\n            {\n                if (x.Contains(&quot;2&quot;))\n                {\n                    yield return x;\n                }\n            }\n        }\n    } \n}\n</code></pre>\n'}, {'answer_id': 69866729, 'author': 'H. Pauwelyn', 'author_id': 4551041, 'author_profile': 'https://Stackoverflow.com/users/4551041', 'pm_score': 2, 'selected': False, 'text': '<p>Nowadays you can use the <code>yield</code> keyword for async streams.</p>\n<blockquote>\n<p>C# 8.0 introduces\xa0async streams, which model a streaming source of data. Data streams often retrieve or generate elements asynchronously. Async streams rely on new interfaces introduced in .NET Standard 2.1. These interfaces are supported in .NET Core 3.0 and later. They provide a natural programming model for asynchronous streaming data sources.</p>\n<p>Source: <a href="https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/tutorials/generate-consume-asynchronous-stream" rel="nofollow noreferrer">Microsoft docs</a></p>\n</blockquote>\n<p>Example below</p>\n<pre class="lang-cs prettyprint-override"><code>using System;\nusing System.Collections.Generic;               \nusing System.Threading.Tasks;\n\npublic class Program\n{\n    public static async Task Main()\n    {\n        List&lt;int&gt; numbers = new List&lt;int&gt;() { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };\n        \n        await foreach(int number in YieldReturnNumbers(numbers))\n        {\n            Console.WriteLine(number);\n        }\n    }\n    \n    public static async IAsyncEnumerable&lt;int&gt; YieldReturnNumbers(List&lt;int&gt; numbers) \n    {\n        foreach (int number in numbers)\n        {\n            await Task.Delay(1000);\n            yield return number;\n        }\n    }\n}\n</code></pre>\n'}]
['https://Stackoverflow.com/questions/39476', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1409/']