Inheritance and the base Keyword
The Idea
Inheritance lets a new class (the child or *derived* class) reuse everything from an existing class (the parent or *base* class) and add or change what it needs.
Simple example: A
Dog is an Animal. Every animal has a name and can eat. The dog inherits those and adds barking.
csharp
class Animal
{
public string Name { get; set; } = "";
public void Eat() => Console.WriteLine($"{Name} is eating.");
}
class Dog : Animal // Dog inherits from Animal
{
public void Bark() => Console.WriteLine($"{Name} says Woof!");
}
var d = new Dog { Name = "Rex" };
d.Eat(); // from Animal
d.Bark(); // from Dog
Constructors and base
csharp
class Animal
{
public string Name { get; }
public Animal(string name) => Name = name;
}
class Dog : Animal
{
public string Breed { get; }
public Dog(string name, string breed) : base(name) // call the parent constructor
{
Breed = breed;
}
}
protected Members
csharp
class Employee
{
protected decimal baseSalary = 1000; // visible to children, hidden from outside
}
class Manager : Employee
{
public decimal Salary => baseSalary + 500;
}
A Realistic Example
csharp
class Vehicle
{
public string Brand { get; init; } = "";
public virtual string Describe() => $"A vehicle by {Brand}";
}
class Truck : Vehicle
{
public int Capacity { get; init; }
public override string Describe() => $"{base.Describe()} with capacity {Capacity} t";
}
Console.WriteLine(new Truck { Brand = "Volvo", Capacity = 20 }.Describe());
| Keyword | Meaning |
|---|---|
: | Inherits from |
base | Refers to the parent class |
virtual | Parent allows children to change this method |
override | Child replaces a virtual method |
sealed | Cannot be inherited or overridden further |
Rules to Remember
- A class can inherit from only one class (but implement many interfaces).
- Every class ultimately inherits from
object, which givesToString(),Equals()andGetHashCode(). - Constructors are not inherited, but the child must call a parent constructor.
Is-a vs Has-a
| Relationship | Use | Example |
|---|---|---|
| Is-a | Inheritance | A Dog is an Animal |
| Has-a | Composition (a field) | A Car has an Engine |
Prefer composition: Deep inheritance trees become hard to change. If the relationship is not clearly 'is a', put an object inside the class instead.
Conclusion
Inheritance reuses code with :. Use base to reach the parent, virtual and override to change behavior and prefer composition when the relationship is 'has a'.
Quick Summary: Child : Parent, base(...) for the parent constructor, virtual/override to customize.

