Inheritance

What is inheritance?

Inheritance is the mechanism by which one class can inherit from another class, allowing it to re-use members, common code and behaviours provided by the a base class.

public class Animal { } public class D...

 

In our interactive example provided above, I've declared a class named Animal. We have then declared another class, named Dog, and using the inheritance syntax with the colon :, it allows us to specify that the Dog class inherits from the Animal class:

public class Dog : Animal

In this relationship, the Animal class is called the base class. It is often also called the "super". The Dog class is called the derived class, and often called the "subclass" or child class. We say that a Dog is an Animal, but an Animal could be a Dog. We say "could", because you can easily implement other forms of Animal:

public class Cat : Animal
{

}

public class Lion : Cat
{

}

This relationship between base and derived classes forms something called an inheritance hierarchy. In C# there are no limits to the number of levels in your inheritance hierarchy.

Page 2 of 18