Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using yield in C#

Tags:

I have a vague understanding of the yield keyword in c#, but I haven't yet seen the need to use it in my code. This probably comes from a lack of understanding of it.

So, what are some typical good usages of yield?

like image 760
Steve Avatar asked Apr 23 '10 07:04

Steve


1 Answers

yield just makes it very simple to implement an enumerator. So if you wanted write a method that returns an IEnumerable<T> it saves you having to create the enumerator class - you just yield one result at a time and the compiler takes care of the details under the covers.

One handy case is to write an "infinite enumerator" that the caller can call as many times as it needs to. Here's an example that generates an infinite series of Fibonacci numbers: http://chrisfulstow.com/fibonacci-numbers-iterator-with-csharp-yield-statements/ (well... theoretically infinite, but in practice limited to the size of UInt64).

like image 89
EMP Avatar answered Sep 22 '22 22:09

EMP