C# Intermediate: OOP, Interfaces & Events

Lesson 1 of 7

Inheritance and Polymorphism

Inheritance lets one class reuse and extend another's members. A derived class inherits fields and methods from a base class, and can override its behavior.

class Animal
{
    public string Name;

    public Animal(string name) => Name = name;

    public virtual string Speak() => $"{Name} makes a sound.";
}

class Dog : Animal
{
    public Dog(string name) : base(name) { }

    public override string Speak() => $"{Name} barks.";
}

Animal a = new Dog("Rex");
Console.WriteLine(a.Speak()); // "Rex barks."

The pieces

  • class Dog : Animal means Dog inherits from Animal.
  • : base(name) calls the base class's constructor.
  • virtual on a base method marks it as overridable, override on the derived method replaces it.
  • Polymorphism: even though a is declared as Animal, calling Speak() runs Dog's version, because the actual object at runtime is a Dog. That's why the last line prints "Rex barks." and not "Rex makes a sound."

sealed and base member access

  • sealed override prevents classes that inherit from Dog from overriding Speak() any further.
  • Inside an overriding method, base.Speak() calls the base class's original implementation.

📝 Inheritance & Polymorphism Quiz

Passing score: 70%
  1. 1.Which keyword lets a derived class replace a base class's virtual method?

  2. 2.A method marked ____ in the base class can be replaced by a derived class using override.

  3. 3.In C#, a class can inherit from more than one base class.