C# ยท Chapter 34 of 46

C# Inheritance

Inheritance lets a class (the derived/child class) acquire fields and methods from another class (the base/parent class), promoting code reuse. In C#, inheritance is expressed with a colon, like `class Dog : Animal`.

Inheritance models an 'is-a' relationship โ€” a Dog is an Animal โ€” allowing shared behavior to live in one place while specialized behavior lives in the derived class.

Syntax
class Derived : Base {
  // additional members
}

Base and derived classes

A derived class inherits all accessible members (not private) of its base class. It can add new members and use the ones inherited from the base class directly.

Calling base members

The `base` keyword lets a derived class call a constructor or method from its base class, useful when you want to extend rather than replace behavior.

Example 1 (csharp)
using System;

class Animal {
  public void Eat() {
    Console.WriteLine("Eating...");
  }
}

class Dog : Animal {
  public void Bark() {
    Console.WriteLine("Woof!");
  }
}

class Program {
  static void Main() {
    Dog d = new Dog();
    d.Eat();
    d.Bark();
  }
}
Output
Eating...
Woof!

Dog inherits Eat() from Animal and also has its own Bark() method.

Example 2 (csharp)
using System;

class Animal {
  public Animal() {
    Console.WriteLine("Animal created");
  }
}

class Dog : Animal {
  public Dog() : base() {
    Console.WriteLine("Dog created");
  }
}

class Program {
  static void Main() {
    Dog d = new Dog();
  }
}
Output
Animal created
Dog created

base() calls the parent class's constructor before the Dog constructor runs.

Key points

  • Inheritance lets a class reuse fields and methods from a base class.
  • The colon (:) syntax expresses inheritance, e.g. `class Dog : Animal`.
  • The base keyword accesses base class members or constructors.
  • C# only supports single inheritance for classes (one direct base class).
๐Ÿ’ก Note: C# does not support multiple class inheritance, but a class can implement multiple interfaces instead.

๐Ÿ“ Quick Quiz

1. What symbol is used to inherit from a class in C#?

2. What does the base keyword do?

3. Can a C# class inherit from multiple classes directly?