The yield keyword
Learn to write iterator methods with yield return.
Iterators with yield return
When a method uses yield return it becomes an iterator method. Each yield return produces a value and pauses execution; when the caller asks for the next value, execution resumes where it left off.
This lets you produce items without loading the whole sequence into memory. The return type is IEnumerable<T>. The compiler generates an IEnumerator class behind the scenes; you need not write one.
Lazy evaluation
A method written with yield return is lazy. Calling it does not run the body at once; the body advances to the first yield return only when a foreach starts on the result.
This means even infinite sequences are possible. A while (true) yield return ... loop produces values until the caller stops. Large data sources can be processed in chunks without waiting for all the data.
Exercise Produce numbers with yield
Write a Numbers() method with return type IEnumerable<int> that produces 1, 2, 3 using yield return. In Main iterate with foreach and print each item.
Show example solution
Write Numbers() returning IEnumerable<int>, put yield return 1; yield return 2; yield return 3; inside. In Main iterate with foreach (var n in Numbers()).
Example solution:
using System;
using System.Collections.Generic;
class Program
{
static IEnumerable<int> Numbers()
{
yield return 1;
yield return 2;
yield return 3;
}
static void Main()
{
foreach (var n in Numbers())
{
Console.WriteLine(n);
}
}
}
Test yourself
-
Match the yield form to its behavior
- yield return
- Produce one value
- yield break
- End iteration
- return List<T>
- Return whole list
- foreach
- Consume iterator
-
Complete the yield statement
yield____1;Show answer
yieldreturn1; -
What does yield return do?
- Runs the method at once
- Loads the whole sequence to memory
- Produces a value and pauses
- Throws an exception
Show answer
Produces a value and pauses — Correct. yield return produces a value and pauses execution.