Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Yield is useful because it saves you space. Most optimizations in programming makes a trade off between space (disk, memory, networking) and processing. Yield as a programming construct allows you to iterate over a collection many times in sequence without needing a separate copy of the collection for each iteration.</p> <p>consider this example:</p> <pre><code>static IEnumerable&lt;Person&gt; GetAllPeople() { return new List&lt;Person&gt;() { new Person() { Name = "George", Surname = "Bush", City = "Washington" }, new Person() { Name = "Abraham", Surname = "Lincoln", City = "Washington" }, new Person() { Name = "Joe", Surname = "Average", City = "New York" } }; } static IEnumerable&lt;Person&gt; GetPeopleFrom(this IEnumerable&lt;Person&gt; people, string where) { foreach (var person in people) { if (person.City == where) yield return person; } yield break; } static IEnumerable&lt;Person&gt; GetPeopleWithInitial(this IEnumerable&lt;Person&gt; people, string initial) { foreach (var person in people) { if (person.Name.StartsWith(initial)) yield return person; } yield break; } static void Main(string[] args) { var people = GetAllPeople(); foreach (var p in people.GetPeopleFrom("Washington")) { // do something with washingtonites } foreach (var p in people.GetPeopleWithInitial("G")) { // do something with people with initial G } foreach (var p in people.GetPeopleWithInitial("P").GetPeopleFrom("New York")) { // etc } } </code></pre> <p>(Obviously you are not required to use yield with extension methods, it just creates a powerful paradigm to think about data.)</p> <p>As you can see, if you have a lot of these "filter" methods (but it can be any kind of method that does some work on a list of people) you can chain many of them together without requiring extra storage space for each step. This is one way of raising the programming language (C#) up to express your solutions better.</p> <p>The first side-effect of yield is that it delays execution of the filtering logic until you actually require it. If you therefore create a variable of type IEnumerable&lt;> (with yields) but never iterate through it, you never execute the logic or consume the space which is a powerful and free optimization.</p> <p>The other side-effect is that yield operates on the lowest common collection interface (IEnumerable&lt;>) which enables the creation of library-like code with wide applicability.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload