Codiqo

Learn C# · lesson 46 of 61 · about 9 minutes

Planning and Modelling

Plan the blacksmith's forge and model its gear with records and classes.

What you'll learn

  • Break a project into types
  • Use records for simple data
  • Copy records with with

The blacksmith's forge

After the dragon hunt, the hero visits the blacksmith with the gold the battle earned. That's the capstone: a shop, built from the same parts as a real one. Each piece of gear, a sword, a shield, a helm and some boots, is just a name, a slot and a price, so it's a record Gear(string Name, string Slot, int Price);. The hero's gold already has rules, so it lives in unit 10's Purse class, and next lesson a Shop class ties the two together. Today the helm is half price: with makes a copy at the new price, and the copy takes its place in the forge.

The project

You'll build Phoebe's Shop: a command-line shop where you spend coins on items for Phoebe.

Plan the types first:

  • Item: a name, a slot (hat, scarf...) and a price. Just data, so a record
  • Wallet: coins that can't go below zero. Has rules, so a class
  • Shop: the catalogue, and buying, which ties them together

record Item(string Name, string Slot, int Price); gives you a constructor, read-only properties, value equality (two items with the same values are equal) and a readable ToString, all in one line.

A class that keeps a rule

var w = new Wallet();
w.Add(50);
Console.WriteLine(w.Coins);

class Wallet
{
    public int Coins { get; private set; }
    public void Add(int n) => Coins += n;
}

Output

50

Records

var hat = new Item("Top hat", "head", 120);
Console.WriteLine(hat);
Console.WriteLine(hat.Price);

var sale = hat with { Price = 90 };
Console.WriteLine($"{sale.Name} now {sale.Price}, was {hat.Price}");
Console.WriteLine(hat == new Item("Top hat", "head", 120));

record Item(string Name, string Slot, int Price);

Output

Item { Name = Top hat, Slot = head, Price = 120 }
120
Top hat now 90, was 120
True

Replacing a record in a list

A record can't be changed once it's made, so the forge never changes the helm itself. forge[2] with { Price = forge[2].Price / 2 } builds a new Gear with the same name and slot, and forge[2] = saleHelm; puts that copy in the list where the old one was. Anything that still holds the old helm sees the old price, which is what makes records safe to pass around.

Now try it yourself

This lesson is free in Codiqo, with 9 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.