c# · level 3 · unit 5 · lesson 3
- meet it
- guess first
- your turn
- fix it
- 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.
guess first
Points on a grid. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
using System;
Point[] points = { new Point(0, 0), new Point(3, 0), new Point(2, 5) };
foreach (Point p in points)
{
Console.WriteLine(Describe(p));
}
string Describe(Point p) => p switch
{
(0, 0) => "the origin",
(_, 0) => "on the x axis",
(var x, var y) => $"at {x},{y}",
};
record Point(int X, int Y);
your turn
Your turn. Decide the delivery charge.
On line 11, choose the total that earns UK customers free delivery. On line 12, write the country for the paid UK arm.
output
press run to see what happens
fix it
The payment log will not compile. Can you fix it?
output
press run to see what happens
- C# says the name
cdoes not exist on line 12. - A type pattern only names the object when you write a name after the type, as the
Casharm does. - Change
Card =>toCard c =>on line 12, then run.
nailed it
you can match the shape of your data. :D
- A type pattern checks the type and names the object.
- A property pattern looks inside, like
{ Total: > 50 }. - Positional patterns match a record's fields in order.
new words in your collection
- type pattern
- property pattern
- positional pattern
This lesson isn’t saved. A free account remembers every lesson you finish.