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
virtualmarks what a subclass may change;overridechanges it.- An
Animal[]holds dogs and cats; each speaks as itself. - The base implementation is the default when nobody overrides.
Keywords and builtins used here
AnimalCatDogSpeakclassforeachinnewoverridepublicstringvarvirtual
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.
Step 3 of 4 in Classes & records, step 20 of 29 in Language basics.