Calling an iterator method runs none of its body. Not the first line, not an argument check, nothing. You get an object back that is willing to produce values later, and that is all.
C#
static IEnumerable<int> Numbers()
{
Console.WriteLine("iterator started");
yield return 1;
yield return 2;
}
static void Main()
{
Console.WriteLine("before call");
var seq = Numbers();
Console.WriteLine("after call");
foreach (var n in seq)
{
Console.WriteLine(n);
}
}
Output
before call after call iterator started 1 2
iterator started prints after after call. The body waited for the foreach.
If you never enumerate seq, that line never prints at all. An iterator you do not consume is a
method you never called.
This is the single most useful sentence in this course: an iterator method call is a promise, not a computation. Every surprise in the next two modules falls out of it.
Try it: Task 1
Open the editor