Lesson 23 of 34 · Classes & Objects
Boss: The Clockwork Quartermaster
The Clockwork Quartermaster blocks the way. Every test you pass deals damage — pass them all to defeat it and claim a loot chest.
The armoury of the Citadel is run by the Clockwork Quartermaster, a brass automaton that has never miscounted a single nail in three hundred years. It hands out equipment only to those who can prove they can keep order themselves. Build a backpack that tracks its gear flawlessly, and the Quartermaster's gears will grind to a halt in respect.
Battle plan
This fight uses every tool from Chapter 4:
- a record for the gear, because two pieces of gear with the same name, weight and value are interchangeable;
- a class with properties for the backpack, because each backpack has its own changing contents;
- constructors that chain to each other and validate their input;
- a static counter shared by all backpacks, and a const default;
- an override of
ToString(), the method every object inherits and thatConsole.WriteLineand string interpolation call to turn an object into text.
public override string ToString() => $"Backpack of {Owner}";
(override is explained properly in the next chapter.)
Assignment
Gear(string Name, int Weight, int Value) is declared for you. Complete Backpack:
- Constructors —
Backpack(owner, capacity)storesOwnerandCapacity; a capacity of 0 or less falls back toDefaultCapacity(20).Backpack(owner)chains to it with the default capacity. Every backpack created increases the staticCreatedcounter;ResetCreated()sets it to 0. - Properties —
Count(number of pieces of gear),TotalWeight,TotalValueandFreeSpace(Capacity - TotalWeight). Add(gear)puts the gear in the backpack and returnstrue— unless it is heavier than the free space, then nothing changes and it returnsfalse.Remove(name)removes the first piece of gear with that name and returnstrue, or returnsfalseif there is none.Has(gear)returnstrueif an equal piece of gear is in the backpack.HeaviestName()returns the name of the heaviest gear (the first one on a tie), or""when the backpack is empty.ToString()returns"Aria's backpack: 12/20 kg, 3 items"— and"1 item"for a single piece of gear.
Premium lesson
Unlock the full Learn C# course
- All 34 lessons, bosses and quizzes — lifetime access
- One payment of $35, no subscription
- Finish within 30 days and claim $10.50 (30%) back
Want more than one course?
The All-Access Pass unlocks all 8 courses and every new one we release, for $120 once.
Keep learning
Need a quick reminder? The C# cheat sheet has every topic of Learn C# on one page.
Lesson last updated on .