<p>I know what <code>yield</code> does, and I've seen a few examples, but I can't think of real life applications, have you used it to solve some specific problem?</p>

<p>(Ideally some problem that cannot be solved some other way)</p>

[{'answer_id': 17133, 'author': 'Nick Berardi', 'author_id': 17, 'author_profile': 'https://Stackoverflow.com/users/17', 'pm_score': 3, 'selected': False, 'text': '<p>actually I use it in a non traditional way on my site <a href="http://www.ideapipe.com" rel="noreferrer">IdeaPipe</a></p>\n\n<pre><code>public override IEnumerator&lt;T&gt; GetEnumerator()\n{\n    // goes through the collection and only returns the ones that are visible for the current user\n    // this is done at this level instead of the display level so that ideas do not bleed through\n    // on services\n    foreach (T idea in InternalCollection)\n        if (idea.IsViewingAuthorized)\n            yield return idea;\n}\n</code></pre>\n\n<p>so basically it checks if viewing the idea is currently authorized and if it is it returns the idea.  If it isn\'t, it is just skipped.  This allows me to cache the Ideas but still display the ideas to the users that are authorized.  Else I would have to re pull them each time based on permissions, when they are only re-ranked every 1 hour.</p>\n'}, {'answer_id': 17171, 'author': 'Mark Cidade', 'author_id': 1659, 'author_profile': 'https://Stackoverflow.com/users/1659', 'pm_score': 1, 'selected': False, 'text': "<p>LINQ's operators on the Enumerable class are implemented as iterators that are created with the yield statement. It allows you to chain operations like Select() and Where() without actually enumerating anything until you actually use the enumerator in a loop, typically by using the <em>foreach</em> statement. Also, since only one value is computed when you call IEnumerator.MoveNext() if you decide to stop mid-collection, you'll save the performance hit of calculating all of the results.</p>\n\n<p>Iterators can also be used to implement other kinds of lazy evaluation where expressions are evaluated only when you need it. You can also use <em>yield</em> for more fancy stuff like coroutines.</p>\n"}, {'answer_id': 17200, 'author': 'Jon Limjap', 'author_id': 372, 'author_profile': 'https://Stackoverflow.com/users/372', 'pm_score': 1, 'selected': False, 'text': '<p>Another good use for yield is to perform a function on the elements of an IEnumerable and to return a result of a different type, for example:</p>\n\n<pre><code>public delegate T SomeDelegate(K obj);\n\npublic IEnumerable&lt;T&gt; DoActionOnList(IEnumerable&lt;K&gt; list, SomeDelegate action)\n{\n    foreach (var i in list)\n        yield return action(i);\n}\n</code></pre>\n'}, {'answer_id': 17202, 'author': 'denis phillips', 'author_id': 748, 'author_profile': 'https://Stackoverflow.com/users/748', 'pm_score': 2, 'selected': False, 'text': '<p>One interesting use is as a mechanism for asynchronous programming esp for tasks that take multiple steps and require the same set of data in each step. Two examples of this would be Jeffery Richters AysncEnumerator <a href="http://msdn.microsoft.com/en-us/magazine/cc163323.aspx" rel="nofollow noreferrer">Part 1</a> and <a href="http://msdn.microsoft.com/en-us/magazine/cc721613.aspx" rel="nofollow noreferrer">Part 2</a>. The Concurrency and Coordination Runtime (CCR) also makes use of this technique <a href="http://msdn.microsoft.com/en-us/library/bb648753.aspx" rel="nofollow noreferrer">CCR Iterators</a>.</p>\n'}, {'answer_id': 17219, 'author': 'Scott Muc', 'author_id': 1894, 'author_profile': 'https://Stackoverflow.com/users/1894', 'pm_score': 0, 'selected': False, 'text': "<p>Using yield can prevent downcasting to a concrete type. This is handy to ensure that the consumer of the collection doesn't manipulate it.</p>\n"}, {'answer_id': 1692705, 'author': 'Ash', 'author_id': 5023, 'author_profile': 'https://Stackoverflow.com/users/5023', 'pm_score': 5, 'selected': True, 'text': '<p>I realise this is an old question (pre Jon Skeet?) but I have been considering this question myself just lately. Unfortunately the current answers here (in my opinion) don\'t mention the most obvious advantage of the yield statement.</p>\n\n<p>The biggest benefit of the yield statement is that it allows you to iterate over very large lists with much more efficient memory usage then using say a standard list.</p>\n\n<p>For example, let\'s say you have a database query that returns 1 million rows.  You could retrieve all rows using a DataReader and store them in a List, therefore requiring list_size * row_size bytes of memory.</p>\n\n<p>Or you could use the yield statement to create an Iterator and only ever store one row in memory at a time.  In effect this gives you the ability to provide a "streaming" capability over large sets of data. </p>\n\n<p>Moreover, in the code that uses the Iterator, you use a simple foreach loop and can decide to break out from the loop as required.  If you do break early, you have not forced the retrieval of the entire set of data when you only needed the first 5 rows (for example).</p>\n\n<p>Regarding:</p>\n\n<pre><code>Ideally some problem that cannot be solved some other way\n</code></pre>\n\n<p>The yield statement does not give you anything you could not do using your own custom iterator implementation, but it saves you needing to write the often complex code needed.  There are very few problems (if any) that can\'t solved more than one way.</p>\n\n<p>Here are a couple of more recent questions and answers that provide more detail:</p>\n\n<p><a href="https://stackoverflow.com/questions/384392/yield-keyword-value-added">Yield keyword value added?</a></p>\n\n<p><a href="https://stackoverflow.com/questions/317619/is-yield-useful-outside-of-linq">Is yield useful outside of LINQ?</a></p>\n'}, {'answer_id': 20363364, 'author': 'Terry Lewis', 'author_id': 1013549, 'author_profile': 'https://Stackoverflow.com/users/1013549', 'pm_score': 0, 'selected': False, 'text': '<p>You can also use <code>yield return</code> to treat a series of function results as a list. For instance, consider a company that pays its employees every two weeks. One could retrieve a subset of payroll dates as a list using this code:</p>\n\n<pre><code>void Main()\n{\n    var StartDate = DateTime.Parse("01/01/2013");\n    var EndDate = DateTime.Parse("06/30/2013");\n    foreach (var d in GetPayrollDates(StartDate, EndDate)) {\n        Console.WriteLine(d);\n    }\n}\n\n// Calculate payroll dates in the given range.\n// Assumes the first date given is a payroll date.\nIEnumerable&lt;DateTime&gt; GetPayrollDates(DateTime startDate, DateTime endDate, int     daysInPeriod = 14) {\n    var thisDate = startDate;\n    while (thisDate &lt; endDate) {\n        yield return thisDate;\n        thisDate = thisDate.AddDays(daysInPeriod);\n    }\n}\n</code></pre>\n'}]
['https://Stackoverflow.com/questions/17125', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1782/']