Skip to content

Checkpoint: Iterators with yield

The Course
•
30 min study

This checkpoint puts the last lesson's iterators to work. Before you write your own, there's one trap to see, because the exercise depends on it.

Fix it: a guard that runs too late

Evens refuses a negative limit. Predict the two lines below, then run it.

When does the guard run? C#
try
{
    IEnumerable<int> evens = Evens(-1);
    Console.WriteLine("Called");
    foreach (int number in evens)
    {
        Console.WriteLine(number);
    }
}
catch (ArgumentOutOfRangeException)
{
    Console.WriteLine("Refused");
}

static IEnumerable<int> Evens(int limit)
{
    ArgumentOutOfRangeException.ThrowIfNegative(limit);
    for (int i = 0; i <= limit; i += 2)
    {
        yield return i;
    }
}
Check your prediction
Text
Called
Refused

Called appears, so the call itself accepted -1. Everything in an iterator method, the guard included, waits until a loop asks for the first value. If the sequence is stored and looped much later, the error appears far from the bad call, or never. Fix it so that Evens(-1) throws at the call and Called is never printed.

Fix it

Split the method in two: a normal method that checks the argument and then returns a private iterator, which does the looping.

C#
try
{
    IEnumerable<int> evens = Evens(-1);
    Console.WriteLine("Called");
    foreach (int number in evens)
    {
        Console.WriteLine(number);
    }
}
catch (ArgumentOutOfRangeException)
{
    Console.WriteLine("Refused");
}

static IEnumerable<int> Evens(int limit)
{
    ArgumentOutOfRangeException.ThrowIfNegative(limit);
    return EvensUpTo(limit);
}

static IEnumerable<int> EvensUpTo(int limit)
{
    for (int i = 0; i <= limit; i += 2)
    {
        yield return i;
    }
}
Text
Refused

Evens has no yield, so it runs at once, like any method. That's how the library's own methods, such as Enumerable.Take, check their arguments.

Build it yourself

Exercise

Generic pipeline steps

Write two generic iterators, using yield return:

  • Distinct2<T>(IEnumerable<T> items) returns each value the first time it appears. It's named Distinct2 so it can't clash with LINQ's own Distinct, which you'll meet on Day 3.
  • Batches<T>(IEnumerable<T> items, int size) returns lists of up to size items. The last list can be shorter, and an empty input returns no lists at all. A size below 1 throws ArgumentOutOfRangeException at the call, before any loop starts, as in the fix above.

Feed 1, 1, 2, 3, 2, 4, 5 through Distinct2, and then through Batches with size 2, printing each batch joined with commas. Then print how many batches an empty input gives, and show that Batches(input, 0) is refused at the call by printing refused at the call.

When it works, it prints:

Text
1,2
3,4
5
0
refused at the call
Your workspace C#
int[] input = { 1, 1, 2, 3, 2, 4, 5 };
Console.WriteLine(input.Length);
Hint 1: the idea

Distinct2 needs memory of what it has seen, and today you already learned a collection for exactly that. Batches fills a list, yields it when it's full, and starts a new list.

Hint 2: a first step

Write Distinct2 first. For Batches, don't forget that when the loop ends, a partly filled list may still be waiting to be returned. Add the guard last, by splitting Batches the way the fix step split Evens.

Show one solution
C#
int[] input = { 1, 1, 2, 3, 2, 4, 5 };

foreach (List<int> batch in Batches(Distinct2(input), 2))
{
    Console.WriteLine(string.Join(",", batch));
}
int emptyBatches = 0;
foreach (List<int> batch in Batches(new int[0], 2))
{
    emptyBatches++;
}
Console.WriteLine(emptyBatches);
try
{
    IEnumerable<List<int>> never = Batches(input, 0);
}
catch (ArgumentOutOfRangeException)
{
    Console.WriteLine("refused at the call");
}

static IEnumerable<T> Distinct2<T>(IEnumerable<T> items)
{
    var seen = new HashSet<T>();
    foreach (T item in items)
    {
        if (seen.Add(item))
        {
            yield return item;
        }
    }
}

static IEnumerable<List<T>> Batches<T>(IEnumerable<T> items, int size)
{
    ArgumentOutOfRangeException.ThrowIfLessThan(size, 1);
    return BatchesOf(items, size);
}

static IEnumerable<List<T>> BatchesOf<T>(IEnumerable<T> items, int size)
{
    var batch = new List<T>();
    foreach (T item in items)
    {
        batch.Add(item);
        if (batch.Count == size)
        {
            yield return batch;
            batch = new List<T>();
        }
    }
    if (batch.Count > 0)
    {
        yield return batch;
    }
}
Text
1,2
3,4
5
0
refused at the call

Each step takes and returns an IEnumerable<T>, so they chain in either order and work on any element type. HashSet.Add returns false for a value already seen, which makes Distinct2 a single test. BatchesOf starts a new list after each yield, because the caller may keep a batch it was given; reusing one list would change batches it already has. Batches itself holds only the guard, so a bad size is refused at the call.

Was this article helpful?

Your response is saved on this device.