Codiqo

Learn C# · lesson 25 of 61 · about 10 minutes

Project: The Arena Shop

Spend the tunnel's gold at the arena shop, built from small methods that each do one job, and say whether the hero could buy what they asked for.

What you'll learn

  • Split a problem into methods
  • Return values from each
  • Change the caller's gold with ref

The arena shop

With the gold from the tunnel, the hero visits the arena shop. It lists what it sells, the hero asks for one item, and the shop says whether the sale worked. Every part is a small method with one job, and the main code only calls them.

One job per method

  • Price(item) gives what an item costs in gold, with a switch expression, and 0 for anything the shop doesn't sell
  • PrintItem(item) prints one line of the list, using Price for the cost
  • Buy(ref gold, item) returns whether the sale worked, and only takes the gold when it did
  • The main code prints the list, reads what the hero wants and calls Buy

The shop's list

PrintItem("potion");
PrintItem("shield");
PrintItem("sword");

// what an item costs in gold, or 0 if the shop doesn't sell it
static int Price(string item) => item switch
{
    "potion" => 2,
    "shield" => 3,
    "sword" => 5,
    _ => 0,
};

// one line of the shop's list
static void PrintItem(string item)
{
    Console.WriteLine($"{item,-8}{Price(item)} gold");
}

Output

potion  2 gold
shield  3 gold
sword   5 gold

Tip

{item,-8} pads the text to 8 characters on the right, so the prices line up whatever the item is.

Now try it yourself

This lesson is free in Codiqo, with 8 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.