c# · level 2 · unit 4 · lesson 4
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
copies a record and changes only what you name.
A record cannot change, but you often want one that is nearly the same. The word with copies a record and changes only the properties you name: monday with { Degrees = 17 }. Everything else is copied across as it was.
The original is left alone, so you can keep both. That makes with handy for a history, where each day's weather is its own record. Change several properties at once by separating them with commas inside the curly brackets.
using System;
var monday = new Weather("Leeds", 14, "cloudy");
var tuesday = monday with { Degrees = 17 };
var wednesday = tuesday with { Degrees = 12, Sky = "rainy" };
Console.WriteLine(monday);
Console.WriteLine(tuesday);
Console.WriteLine(wednesday);
record Weather(string Town, int Degrees, string Sky); Monday still says 14 and cloudy at the end, because nothing ever changed it.
guess first
The basket gets bigger. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
using System;
var basket = new Basket("apples", 3);
var bigger = basket with { Count = 5 };
Console.WriteLine($"{basket.Count} {bigger.Count} {bigger.Fruit}");
record Basket(string Fruit, int Count);
your turn
Your turn. Level up a player.
Name your player on line 3. On line 4, copy them up to level 2. On line 5, copy that player with Health set to 60. Press run.
output
press run to see what happens
fix it
The sale price never shows. Fix it!
output
press run to see what happens
- It shows 120, the old price. Which record does line 5 read the price from?
withleftticketalone. The new price lives in the copy calledsale.- Change
ticket.Pricetosale.Priceon line 5, then press run.
nailed it
you can copy and change in one go. :D
withcopies a record and changes what you name.- The original record never changes.
- Separate several changes with commas.
new words in your collection
- with
This lesson isn’t saved. A free account remembers every lesson you finish.