C# Inheritance
Inheritance lets one class build on another. The new class — the derived class or subclass — automatically gets the fields, properties and methods of the existing base class, and can add its own members or change inherited behaviour. It models an "is a" relationship: a Car is a Vehicle, a Manager is an Employee.
Deriving a class
Use a colon after the class name to specify the base class:
using System;
var car = new Car { Brand = "Saab", Doors = 4 };
car.Honk(); // inherited from Vehicle
Console.WriteLine(quot;{car.Brand} with {car.Doors} doors");
var bike = new Bicycle { Brand = "Trek" };
bike.Honk();
bike.RingBell();
class Vehicle
{
public string Brand { get; set; } = "";
public void Honk() => Console.WriteLine(quot;{Brand}: Beep beep!");
}
class Car : Vehicle
{
public int Doors { get; set; }
}
class Bicycle : Vehicle
{
public void RingBell() => Console.WriteLine(quot;{Brand}: Ring ring!");
}Saab: Beep beep!
Saab with 4 doors
Trek: Beep beep!
Trek: Ring ring!
Car and Bicycle each wrote only what is special about them; everything common lives once in Vehicle.
Calling the base constructor
Constructors are not inherited. If the base class needs constructor arguments, the derived constructor passes them on with : base(...). The base constructor always runs first.
using System;
var m = new Manager("Iris", 5200m, 6);
Console.WriteLine(m.Describe());
class Employee
{
public string Name { get; }
public decimal Salary { get; }
public Employee(string name, decimal salary)
{
Console.WriteLine("Employee constructor");
Name = name;
Salary = salary;
}
public string Describe() => quot;{Name} earns {Salary}";
}
class Manager : Employee
{
public int TeamSize { get; }
public Manager(string name, decimal salary, int teamSize) : base(name, salary)
{
Console.WriteLine("Manager constructor");
TeamSize = teamSize;
}
}Employee constructor
Manager constructor
Iris earns 5200
Overriding behaviour: virtual and override
A base class marks a method virtual to say "subclasses may replace this". A subclass then provides its own version with override. Inside the override, base.Method() calls the original implementation.
using System;
Animal[] zoo = { new Animal("Generic"), new Dog("Rex"), new Cat("Tom") };
foreach (var a in zoo)
Console.WriteLine(a.Speak());
class Animal
{
public string Name { get; }
public Animal(string name) => Name = name;
public virtual string Speak() => quot;{Name} makes a sound";
}
class Dog : Animal
{
public Dog(string name) : base(name) { }
public override string Speak() => quot;{Name} barks";
}
class Cat : Animal
{
public Cat(string name) : base(name) { }
public override string Speak() => base.Speak() + " (a quiet meow)";
}Generic makes a sound
Rex barks
Tom makes a sound (a quiet meow)
Notice that the array has type Animal[], yet each element runs its own Speak. That is polymorphism, the topic of the next lesson.
The inheritance chain and System.Object
C# supports single inheritance for classes: a class has exactly one direct base class. Chains can be as deep as you like (Animal → Mammal → Dog), and every class ultimately derives from System.Object, which is why all objects have ToString(), Equals() and GetHashCode().
using System;
var puppy = new Puppy();
Console.WriteLine(puppy is Puppy);
Console.WriteLine(puppy is Dog);
Console.WriteLine(puppy is Animal);
Console.WriteLine(puppy is object);
Console.WriteLine(typeof(Puppy).BaseType.Name);
class Animal { }
class Dog : Animal { }
class Puppy : Dog { }True
True
True
True
Dog
Sealed classes
Mark a class sealed to forbid inheriting from it. string is sealed, for example. You can also seal an individual override (sealed override) so that further subclasses cannot change it again.
sealed class Config { }
class MyConfig : Config { } // error CS0509: cannot derive from sealed type 'Config'Summary
| Keyword | Meaning |
|---|---|
class B : A |
B inherits from A |
base(...) |
Call the base class constructor |
base.M() |
Call the base version of a member |
virtual |
Member may be overridden |
override |
Replace a virtual member |
sealed |
Class cannot be inherited / override cannot be overridden again |
protected |
Visible to derived classes only |
Tip: Use inheritance only for genuine "is a" relationships. For "has a" relationships (a
Carhas anEngine), give the class a field of that type instead — this is called composition and is often more flexible.
Test yourself
How many base classes can a C# class inherit from directly?
- None
- One
- Two
- Unlimited
Which keyword lets a subclass replace a virtual method?
- new
- base
- override
- sealed
When creating a Manager : Employee, which constructor body runs first?
- Manager
- Employee
- They run in parallel
- Only Manager's runs