Deferred Execution
From docs.microsoft.com
Deferred execution means that the evaluation of an expression is delayed until its realized value is actually required. Deferred execution can greatly improve performance when you have to manipulate large data collections, especially in programs that contain a series of chained queries or manipulations. In the best case, deferred execution enables only a single iteration through the source collection.
The LINQ technologies make extensive use of deferred execution in both the members of core System.Linq classes and in the extension methods in the various LINQ namespaces, such as System.Xml.Linq.Extensions.
Deferred execution is supported directly in the C# language by the yield keyword (in the form of the yield-return
statement) when used within an iterator block. Such an iterator must return a collection of type IEnumerator or IEnumerator (or a derived type).
Code Example
Not sure about real world application but this is a code example based on a post from stack overflow.
1 | public class YieldDemo |
This results in
References
- https://stackoverflow.com/questions/44798975/trouble-understanding-yield-in-c-sharp?noredirect=1&lq=1
- https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/linq/deferred-execution-and-lazy-evaluation-in-linq-to-xml
- https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/yield