×

c# · level 3 · unit 5 · lesson 3

  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 check an object's type and look inside it.

A checks what an object really is and names it in one go: Box b => .... Inside that arm, b is a Box, with every Box property ready to use. This shines when one list holds many kinds of thing: parcels, payments or messages.

A looks inside: { Grams: <= 100 } matches an object whose Grams is 100 or less, and Box { Fragile: true } checks the type and a property at once. Records also allow a , which matches their fields in order: (0, 0).

using System;
using System.Collections.Generic;

var parcels = new List<object> { new Letter(80), new Box(2.5, true), new Box(12, false), "a brick" };
foreach (object parcel in parcels)
{
    Console.WriteLine(Postage(parcel));
}

string Postage(object parcel) => parcel switch
{
    Letter { Grams: <= 100 } => "1st class stamp",
    Letter => "large letter",
    Box { Fragile: true } b => $"{b.Kilos}kg box, handle with care",
    Box b => $"{b.Kilos}kg box",
    _ => "cannot send that",
};

record Letter(int Grams);
record Box(double Kilos, bool Fragile);

object is the type every other type comes from, so this list can hold anything.