Yield and iterator state
Yield and iterator state
An iterator method generates a sequence incrementally with yield return. Instead of producing every value before returning, it creates an enumerable or enumerator that advances through the method when requested. This makes the moment of execution observable and lets callers stop before all values are produced.
Examples target the proposed C# 14 / .NET 10 console baseline. Each is a separate Program.cs; expected outputs are reasoned, not executed.
Trace suspension and resumption
Calling an iterator method that returns IEnumerable<T> does not execute its body immediately. GetEnumerator obtains an enumerator; MoveNext advances it and reports whether a value is available. Current is valid after a successful MoveNext. The compiler normally generates a state machine to retain state across suspensions.
using System;using System.Collections.Generic;var sequence = Shelves();Console.WriteLine("Created");using var cursor = sequence.GetEnumerator();while (cursor.MoveNext()) Console.WriteLine($"Read {cursor.Current}");static IEnumerable<int> Shelves(){ Console.WriteLine("Start"); yield return 10; Console.WriteLine("Resume"); yield return 20; Console.WriteLine("End");}The first MoveNext starts the body, the second resumes it, and the final one runs to completion.
Expected output (reasoned, not executed):
CreatedStartRead 10ResumeRead 20EndStop generating values
yield break finishes enumeration early. A foreach loop normally calls MoveNext for you and stops when it returns false. Use a finite limit or a clear termination condition.
using System;using System.Collections.Generic;using System.Linq;Console.WriteLine(string.Join(",", Available(new[] { 3, 4, 0, 7 })));Console.WriteLine(Available(Array.Empty<int>()).Count());static IEnumerable<int> Available(int[] quantities){ foreach (int quantity in quantities) { if (quantity == 0) yield break; yield return quantity; }}The zero is a sentinel for ending the sequence; 7 is never reached. An empty input produces no values.
Expected output (reasoned, not executed):
3,40Bound lazy work
An iterator is not a saved list. Re-enumerating normally starts a fresh traversal of the method. Take can limit how many elements are requested from a suitable streaming source; it cannot protect an upstream operator that buffers everything first.
using System;using System.Collections.Generic;using System.Linq;var labels = Labels(5);Console.WriteLine(string.Join(",", labels.Take(2)));Console.WriteLine(string.Join(",", labels.Take(1)));static IEnumerable<int> Labels(int count){ for (int i = 1; i <= count; i++) { Console.WriteLine($"Generating {i}"); yield return i; }}Each traversal requests only its needed values. The loop local starts again for the second enumeration.
Expected output (reasoned, not executed):
Generating 1Generating 21,2Generating 11Common mistakes and edge cases
Do not read Current before MoveNext succeeds or after it returns false. Do not assume a sequence caches prior values or supports Reset. Iterator locals survive suspension, but the exact generated class layout is an implementation detail. Avoid using side effects merely to observe production iteration; the logging here is intentional teaching instrumentation.
Practice and recap
Write an iterator that yields odd positive shelf IDs up to 9, then use Take(3). Log before each yield and enumerate twice. Explain the second traversal.
Hint: Start at 1 and increment by 2; bound the loop at 9.
Learning objective: Trace an iterator across MoveNext calls. See the accompanying manual practice and knowledge check.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Yield and iterator state — knowledge check
Apply the lesson concepts to the following scenarios.
When does a normal iterator body begin executing?
What does yield return do?
What does yield break do?
What should Current follow?
Does a new enumeration of this iterator reuse cached output?