Visual Studio 2005 and C# 2.0 introduced the yield
keyword. The yield
keyword is used within an iterator member as a means to effectively implement an IEnumerable
interface without needing to implement the entire IEnumerable
interface.
Iterator members are members that return a type of IEnumerable
or IEnumerable<T>
, and return individual elements in the enumerable via yield return
, or deterministically terminates the enumerable via yield break
. These members can be anything that can return a value, such as methods, properties, or operators. An iterator that returns without calling yield break
has an implied yield break
, just as a void method has an implied return
.
Iterators operate on a sequence but process and return each element as it is requested. This means that iterators implement what is known as deferred execution. Deferred execution is when some or all of the code, although reached in terms of where the instruction pointer is in relation...