c# · level 3 · unit 4 · lesson 1
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
hands out items one at a time.
foreach does not need a list. It needs an : anything that can hand out items one after another. Lists, arrays and LINQ queries all are. Return IEnumerable<T> from a method and callers can loop over it without caring how the items are made.
The neatest way to write one is an : a method that uses yield return. Each yield return hands one item to the loop and pauses the method right there. When the loop asks for the next item, the method carries on from where it paused.
yield break ends the iterator early, like return in a normal method.
using System;
using System.Collections.Generic;
foreach (string slot in Slots(9, 12))
{
Console.WriteLine(slot);
}
IEnumerable<string> Slots(int from, int to)
{
for (int hour = from; hour < to; hour++)
{
yield return $"{hour}:00";
yield return $"{hour}:30";
}
} Nothing is stored: each time slot is made at the moment the loop asks for it.
guess first
Who prints first? What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
using System;
using System.Collections.Generic;
foreach (int n in Numbers())
{
Console.WriteLine($"got {n}");
}
IEnumerable<int> Numbers()
{
Console.WriteLine("start");
yield return 1;
Console.WriteLine("middle");
yield return 2;
}
your turn
Your turn. Count down to lift off.
Choose where to count down from on line 4. Then, on line 10, hand each number to the caller from inside the loop.
output
press run to see what happens
fix it
The page list will not compile. Can you fix it?
output
press run to see what happens
- C# refuses
return nullinside an iterator on line 14. How does an iterator say there is nothing more? - An iterator cannot
returna value. It ends early with its own pair of words. - Change
return null;toyield break;on line 14, then run.
nailed it
you can make sequences of your own. :D
foreachwalks anything that is anIEnumerable<T>.yield returnhands out one item, then pauses.yield breakends an iterator early.
new words in your collection
- IEnumerable
- iterator
- yield return
This lesson isn’t saved. A free account remembers every lesson you finish.