×

c# · level 3 · unit 5 · 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

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.