typestar

Inheritance in C#

One base contract, many behaviors, chosen at run time.

Animal[] zoo = { new Dog(), new Cat() };
foreach (var animal in zoo)
{
    Console.WriteLine(animal.Speak());
}

class Animal
{
    public virtual string Speak() => "...";
}

class Dog : Animal
{
    public override string Speak() => "woof, says the dog";
}

class Cat : Animal
{
    public override string Speak() => "meow, says the cat";
}

How it works

  1. virtual marks what a subclass may change; override changes it.
  2. An Animal[] holds dogs and cats; each speaks as itself.
  3. The base implementation is the default when nobody overrides.

Keywords and builtins used here

The run, in numbers

Lines
20
Characters to type
325
Tokens
80
Three-star pace
90 tpm

At the three-star pace of 90 tokens a minute, this run takes about 53 seconds.

Type this snippet

Step 3 of 4 in Classes & records, step 20 of 29 in Language basics.

← Previous Next →

Inheritance in other languages