C# Inheritance
In C#, inheritance lets one class reuse the fields, properties, and methods of another class. This helps you avoid repeating code and lets you organize your classes into a clear family tree.
What Is Inheritance?
Inheritance is one of the core ideas in object-oriented programming. It allows a new class to be built on top of an existing class, inheriting everything the existing class already has. The class that gives away its members is called the base class (or parent class), and the class that receives them is called the derived class (or child class).
In C# we use the colon symbol (:) to say that one class inherits from another. Think of it like this: a Dog is a kind of Animal, so the Dog class can inherit from the Animal class and automatically get all of the Animal features for free.
A base class and a derived class
class Vehicle // base class
{
public string Brand = "Ford";
public void Honk()
{
Console.WriteLine("Beep beep!");
}
}
class Car : Vehicle // derived class
{
public string ModelName = "Mustang";
}
class Program
{
static void Main()
{
Car myCar = new Car();
myCar.Honk(); // inherited from Vehicle
Console.WriteLine(myCar.Brand + " " + myCar.ModelName);
}
}
// Output:
// Beep beep!
// Ford MustangThe base Keyword
Sometimes a derived class wants to call a member that belongs to its base class. The base keyword gives you a way to reach the parent's version of a method, field, or constructor. This is very useful when a child class adds extra behaviour but still wants the original behaviour to run too.
Using base to call the parent
class Animal
{
public virtual void Describe()
{
Console.WriteLine("I am an animal.");
}
}
class Cat : Animal
{
public override void Describe()
{
base.Describe(); // run the parent version first
Console.WriteLine("I am also a cat.");
}
}
// Calling new Cat().Describe() prints both lines.The sealed Keyword
If you want to stop other classes from inheriting from a class, mark it with the sealed keyword. A sealed class cannot be used as a base class. This is helpful when a class is complete and should not be extended.
Inheritance keeps your code clean and organized. Instead of writing the same field or method in many classes, you write it once in a base class and let every derived class share it.
Exercise: C# Inheritance
How many classes can a single C# class directly inherit from?