Skip to content

2.4 — IEnumerator, yield return, Deferred Execution

← Roadmap · Section: 2. Collections, LINQ and Async Prev: 2.3 Concurrent collections · Next: 2.5 LINQ basics

Markers: ⭐ 💻 · Confidence: 🔴 · Last reviewed: —


TL;DR

  • yield return lets you produce items one at a time, on demand, instead of building a whole list first.
  • A method containing yield return does not run at all until someone starts looping over its result. That surprises people.
  • The compiler rewrites the method into a hidden state machine class that remembers where it got to.

The concept

Normally a method does all its work and then hands back a finished result. If it returns a thousand items, all thousand exist in memory before the caller sees the first one.

yield return changes that. It lets the method hand back one item, pause, and wait. When the caller asks for the next one, the method resumes exactly where it stopped.

A picture: a vending machine versus a delivery van.

A normal method is the delivery van — it turns up with the entire order at once, and you need somewhere to put all of it. A yield return method is the vending machine — you press the button, one item drops out, and nothing else moves until you press again.

Why does that matter? Two reasons:

  • Memory. Reading a million-line file into a List<string> needs memory for a million strings. Yielding them one at a time needs memory for one.
  • Stopping early. If you only want the first match, the vending machine stops after the first press. The van has already driven the whole route.

How it works

The basic shape

public IEnumerable<int> GetNumbers()
{
    Console.WriteLine("  starting");
    yield return 1;
    Console.WriteLine("  after 1");
    yield return 2;
    Console.WriteLine("  after 2");
    yield return 3;
}

Now watch the execution order carefully — this is the part that catches people out:

Console.WriteLine("calling the method");
var numbers = GetNumbers();
Console.WriteLine("method returned");

foreach (var n in numbers)
    Console.WriteLine($"got {n}");

Output:

calling the method
method returned          ← the method body has NOT run yet!
  starting
got 1
  after 1
got 2
  after 2
got 3

Notice that "starting" prints after "method returned". Calling the method did nothing at all. The body only began running when foreach asked for the first item.

What the compiler actually does

It rewrites your method into a hidden class that implements IEnumerator<T> and remembers a position number. Roughly:

// Compiler-generated, simplified
class Hidden : IEnumerator<int>
{
    int _state = 0;
    public int Current { get; private set; }

    public bool MoveNext()
    {
        switch (_state)
        {
            case 0: Current = 1; _state = 1; return true;   // stop after 'yield return 1'
            case 1: Current = 2; _state = 2; return true;
            case 2: Current = 3; _state = 3; return true;
            default: return false;                          // no more items
        }
    }
}

And foreach is really just this loop:

var e = numbers.GetEnumerator();
while (e.MoveNext())              // "is there another? if so, load it into Current"
{
    var n = e.Current;
}

So yield return is a pause point. Each MoveNext() runs the method until the next yield return, then freezes it again.

yield break

Stops the sequence early:

public IEnumerable<int> TakeUntilNegative(IEnumerable<int> source)
{
    foreach (var n in source)
    {
        if (n < 0) yield break;    // stop producing, cleanly
        yield return n;
    }
}

The memory win

// Loads the ENTIRE file into memory first
public List<string> ReadAllLines(string path)
{
    var lines = new List<string>();
    foreach (var line in File.ReadLines(path))
        lines.Add(line);
    return lines;
}
// A 2 GB log file needs 2 GB of RAM. Might not even fit.
// Reads one line at a time
public IEnumerable<string> ReadLines(string path)
{
    using var reader = new StreamReader(path);
    string? line;
    while ((line = reader.ReadLine()) is not null)
        yield return line;
}
// A 2 GB file uses memory for ONE line.

And with the second version, stopping early actually stops:

var firstError = ReadLines("huge.log").First(l => l.Contains("ERROR"));
// If the error is on line 3, the file reader closes after line 3.
// The other two gigabytes are never touched.

Note the using inside the iterator. When the caller stops looping — whether normally, by breaking out, or because of an exception — the compiler runs the disposal properly. That is handled for you.


⚠️ The validation trap

This is the one to remember, and it is a genuinely common bug.

public IEnumerable<Order> GetOrders(Guid customerId)
{
    if (customerId == Guid.Empty)
        throw new ArgumentException("Invalid id", nameof(customerId));   // ← never runs on time

    foreach (var order in _db.Orders.Where(o => o.CustomerId == customerId))
        yield return order;
}

Because the method contains yield return, the entire body is deferred — including the validation at the top:

var orders = GetOrders(Guid.Empty);   // NO exception here. Nothing ran.

// ... 50 lines of other code ...

foreach (var o in orders) { }          // exception thrown HERE, far from the cause

The stack trace points at the foreach, not at the bad argument. Debugging that is miserable.

The fix: split it into two methods. An outer normal method that validates immediately, and an inner iterator:

public IEnumerable<Order> GetOrders(Guid customerId)
{
    if (customerId == Guid.Empty)
        throw new ArgumentException("Invalid id", nameof(customerId));

    return Iterate();      // this line runs immediately

    IEnumerable<Order> Iterate()      // a local function — see 1.24
    {
        foreach (var order in _db.Orders.Where(o => o.CustomerId == customerId))
            yield return order;
    }
}

Now GetOrders is a normal method — no yield in its own body — so its validation runs the moment it is called. Only Iterate is deferred.


Code

A realistic streaming example — processing a large CSV without loading it all:

public IEnumerable<Order> ParseOrders(string path)
{
    if (!File.Exists(path))
        throw new FileNotFoundException(path);      // runs immediately

    return Parse();

    IEnumerable<Order> Parse()
    {
        using var reader = new StreamReader(path);
        reader.ReadLine();                          // skip the header row

        string? line;
        while ((line = reader.ReadLine()) is not null)
        {
            var parts = line.Split(',');
            yield return new Order
            {
                Id       = Guid.Parse(parts[0]),
                Customer = parts[1],
                Total    = decimal.Parse(parts[2])
            };
        }
    }
}

Used with LINQ, the whole pipeline stays lazy:

var firstBigOrder = ParseOrders("orders.csv")
    .Where(o => o.Total > 10_000)
    .FirstOrDefault();

// Reads the file line by line and STOPS at the first match.
// A 5 GB file where the match is on line 12 reads 12 lines.

Interview questions

Q: What does yield return do?

It turns a method into an iterator that produces values one at a time instead of building and returning a whole collection. Each yield return hands one item back and pauses the method; when the caller asks for the next item, execution resumes from exactly that point. The compiler implements this by rewriting the method into a hidden class that implements IEnumerator<T> and tracks a state number, so the "pause and resume" is really a switch statement on that state.

Q: When is the body of an iterator method executed?

Not when you call it. Calling it just creates the state machine object and returns immediately. The body only starts running when something calls MoveNext on the enumerator, which in practice means when a foreach begins or when a LINQ operator that forces execution runs. That is why it is called deferred execution, and it is why argument validation inside an iterator method fires at the wrong time.

Q: What is wrong with validating arguments inside an iterator method?

The validation is deferred along with everything else, so it does not throw when the method is called — it throws whenever the caller eventually enumerates the result, which might be much later and in a completely different part of the code. The stack trace then points at the foreach rather than at the bad argument. The fix is to split it: a normal outer method that validates and then returns a local iterator function, so validation runs eagerly and only the iteration is deferred.

Q: What is the benefit of an iterator over just returning a List?

Memory and early exit. A List has to hold everything at once, so reading a two-gigabyte file means two gigabytes of RAM. An iterator holds one item at a time. And because items are produced on demand, an operation like First or Any stops the producer as soon as it has what it needs, so you never do the work of generating the rest. The trade-off is that the sequence can only be walked forward, and walking it twice does the work twice.


Traps ⚠️

  • The whole method body is deferred, including validation. Split into an outer validating method plus an inner iterator.
  • Enumerating twice runs the method twice. For a file read or a database query that is two full passes. See 2.6.
  • You cannot use ref or out parameters in an iterator method. The compiler rejects it, because those cannot be stored in the state machine.
  • try/catch around a yield return is not allowed. You can use try/finally, and using works, but you cannot catch around a yield point.
  • Iterators are forward-only. No index, no Count, and no going back.
  • Captured variables are shared with the state machine. If the caller changes a variable the iterator captured, the iterator sees the new value on the next MoveNext.
  • IEnumerable is not thread-safe. Two threads enumerating the same iterator instance will corrupt its state.


Sources