| Start |
|---|
| Simple Usage The The following example has a yield return statement that's inside a Then you can call it: Console Output Live Demo on .NET Fiddle (opens new window) Each iteration of the |
| Correctly checking arguments An iterator method is not executed until the return value is enumerated. It's therefore advantageous to assert preconditions outside of the iterator. Calling Side Code (Usage): Output: 1 Live Demo on .NET Fiddle (opens new window) When a method uses This means you won't find out about invalid arguments (passing When using C# 7+, the |
| Early Termination You can extend the functionality of existing The above method would iterate from a given Output: 1 |
More Pertinent Usage There are other ways of getting an |
| Lazy Evaluation Only when the Consider the following example: This will output: Starting iteration As a consequence:
|
| Try...finally If an iterator method has a yield inside a Given the function: When calling: Then it prints: 1 When calling: Then it prints: 1 |
| Using yield to create an IEnumerator The While the This can be useful if we want to create our own class which implements (Note that this particular example is just illustrative, and could be more cleanly implemented with a single iterator method returning an |
| Eager evaluation The The following code shows this: Calling |
Return another Enumerable within a method returning Enumerable |
Lazy Evaluation Example: Fibonacci Numbers How it works under the hood (I recommend to decompile resulting .exe file in IL Disaambler tool):
Also note, that 10001th number is 468 bytes long. State machine only saves |
| The difference between break and yield break Using The confusing part is that both of the keywords (or key phrases) make sense only within loops ( It's important to realize that once you use the Let's see some examples: Syntax
RemarksPutting the The
As the Further reading |
Read Article
https://develop.horje.com/learn/1434/reference