c# · level 3 · unit 5 · lesson 2
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
Patterns can compare with < and >=, and combine with and.
An arm does not have to match one exact value. A compares: < 0, >= 90. Arms run top to bottom, so a grade table reads naturally: >= 90 => "A", then >= 80 => "B", and so on down.
A joins or flips patterns with plain words: >= 13 and <= 19 for teenagers, "Sat" or "Sun" for weekends, not null for anything present. The same patterns work after is: if (age is >= 18 and < 65).
If an earlier arm already covers a later one, the later arm could never run, so C# stops with CS8510.
using System;
int[] readings = { -4, 3, 18, 31 };
foreach (int temp in readings)
{
Console.WriteLine($"{temp}C: {Describe(temp)}");
}
string Describe(int celsius) => celsius switch
{
< 0 => "freezing",
>= 0 and < 10 => "cold",
>= 10 and < 25 => "mild",
_ => "hot",
}; >= 0 and < 10 could be < 10 here, because the arm above already caught everything below 0.
guess first
Three tickets. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
using System;
Console.WriteLine($"{Ticket(4)} {Ticket(16)} {Ticket(70)}");
string Ticket(int age) => age switch
{
< 5 => "free",
< 16 => "child",
>= 65 => "senior",
_ => "adult",
};
your turn
Your turn. Spot the weekend.
On line 6, write a pattern after is that matches both weekend days, joined with or.
output
press run to see what happens
fix it
The grade table will not compile. Can you fix it?
output
press run to see what happens
- C# says the pattern on line 12 has already been handled. Which arm would catch 88 first?
- Every mark of 70 or more is also 50 or more, so the
passarm swallows them all. - Swap lines 11 and 12 so
>= 70comes first, then run.
nailed it
your patterns can compare now. :D
- Relational patterns compare, like
< 0or>= 90. and,orandnotjoin and flip patterns.- Put the narrowest arms first.
new words in your collection
- relational pattern
- logical pattern
This lesson isn’t saved. A free account remembers every lesson you finish.