Inheritance

View saved

Derive from a base class

A derived class inherits members from its base.

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

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

Animal a = new Dog();
Console.WriteLine(a.Speak());

Call the base constructor

Pass values up with base(...).

class Person
{
    public string Name { get; }
    public Person(string name) => Name = name;
}

class Learner : Person
{
    public Learner(string name) : base(name) { }
}

Prefer composition when unsure

Inheritance is powerful but couples types. Favor it for true is-a relationships.

Inheritance tips

  • Mark overridable methods virtual
  • Seal classes you do not want extended
  • Avoid deep inheritance hierarchies
  • Interfaces (next) often replace multiple inheritance needs

Comments

One comment per signed-in account. Comments are saved with this page’s URL.