×

c# · level 3 · unit 4 · lesson 2

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

An iterator can go on forever, safely.

Iterators are : they do no work until someone asks for the next item, and they stop the moment nobody asks. That makes a strange thing possible: an . while (true) inside an iterator is fine, because each yield return pauses it.

The caller decides how much to take. Take(5) asks for five items, then stops asking. TakeWhile(n => n < 60) keeps asking while a test passes. Skip(2) throws the first two away. Never call Count() or ToList() on an infinite sequence: they would wait forever.

using System;
using System.Collections.Generic;
using System.Linq;

var firstFive = Squares().Take(5);
Console.WriteLine(string.Join(" ", firstFive));
var small = Squares().Skip(2).TakeWhile(n => n < 60);
Console.WriteLine(string.Join(" ", small));

IEnumerable<int> Squares()
{
    int n = 1;
    while (true)
    {
        yield return n * n;
        n++;
    }
}

Each query calls Squares() again, so both start from 1.