Codiqo

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

Inheritance

Post the troll bounty: build a class on top of another with :, reuse its members, and change behaviour with virtual and override.

What you'll learn

  • Inherit with class Child : Parent
  • Call the parent constructor with base
  • Override virtual methods

The troll bounty

The quest board gets a bounty: 30 gold for dealing as much damage as a troll has HP. A bounty is still a quest, with a title, a reward and a Done that only Complete() can set, so rather than copy Quest, the battle writes class Bounty : Quest. Its constructor hands the title and reward to base(title, reward) and sets the one new property, Needed. AddDamage() adds up the boss hits and calls the inherited Complete() once there's enough, and ToString() is overridden to add the progress to what Quest already prints, like Troll bounty: done (+30 gold) [30/30].

Is-a relationships

class Dog : Animal means a Dog is an Animal: it gets all of Animal's public members.

  • : base(name) passes values to the parent's constructor
  • Mark a method virtual in the parent to allow children to replace it
  • Replace it with override in the child
  • base.Describe() calls the parent's version
  • protected members are visible to children but not to outside code

A child gets its parent's members

var d = new Dog();
Console.WriteLine(d.Legs);
Console.WriteLine(d.Bark());

class Animal
{
    public int Legs = 4;
}

class Dog : Animal
{
    public string Bark() => "Woof";
}

Output

4
Woof

Changing what children do

A child can also replace what it inherits. The parent marks a method virtual, the child writes its own version with override, and the object's real type decides which one runs, even through a variable of the parent's type. Inside the override, base.Describe() still reaches the parent's version, so a child can add to it instead of starting again.

Animals

Animal[] zoo = { new Animal("Generic"), new Dog("Rex"), new Penguin("Phoebe") };
foreach (Animal a in zoo) Console.WriteLine(a.Describe());

class Animal
{
    public string Name { get; }
    public Animal(string name) => Name = name;
    public virtual string Sound() => "...";
    public virtual string Describe() => $"{Name} says {Sound()}";
}

class Dog : Animal
{
    public Dog(string name) : base(name) { }
    public override string Sound() => "Woof";
}

class Penguin : Animal
{
    public Penguin(string name) : base(name) { }
    public override string Sound() => "Squawk";
    public override string Describe() => base.Describe() + " and slides on ice";
}

Output

Generic says ...
Rex says Woof
Phoebe says Squawk and slides on ice

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.