DEV Community

yashaswi
yashaswi

Posted on

[Post-3][LINQ] — Yield

Yield in C# is very tricky concept and would take at least a couple of reads to understand its use or purpose. Lets try to de -mystify this concept and understand its use and purpose in this article. Get buckled up for an interesting read.

***Enumerable **and ***Enumerator *are foundational concepts to understanding of **Yield. Any method that does *yield return should return an **Iterator. **For a method to return an Iterator, its return type must of be one of the below types.

  • IAsyncEnumerable

  • IEnumerable

  • IEnumerable

  • IEnumerator

  • IEnumerator

If you are wondering what these * *declarations mean, don’t worry, these are part of *Generics, *which will be covered in necessary proportions in the upcoming chapters. For now you can ignore them.

Add breakpoints at line 17 and at lines 22 till 26 then run the code. You’ll notice that the code does not go into *YieldNumber() *method. It bypasses the method and breaks directly at line 17.

The reason behind this functionality is that, yield return does a Lazy evaluation.

Lazy evaluation in this context means that, until the YieldNumber() method is iterated the yield return statements are not executed.

Now uncomment the line from 12 to 16 and execute the program.

Notice that the program now goes into the *YieldNumber *method and breaks at each yield return statement for each iteration of the while loop.

In the next post lets talk about how Yield and LINQ are related and understand performance benefits of LINQ.

The posts in this publication are intentionally kept short for easier learning.

Any comment from you is greatly appreciated. Thanks!!!

Discussion (0)