C# Inheritance & Polymorphism

Base classes, virtual and override.

✍️ 2 exercises in this lesson
  • class Dog : Animal inherits from Animal.
  • Mark base methods virtual and replace them with override.
  • base calls the parent constructor or method.
  • abstract classes and methods must be completed by subclasses.
  • sealed prevents further inheritance.

Key Takeaways: C# Inheritance & Polymorphism

Mastering C# Inheritance & Polymorphism helps you write clean and reliable C# code. Follow standard conventions, test edge cases, and keep logic simple. Try running the code example below and complete the exercises to build confidence.

C# Inheritance & Polymorphism Code Example

C#
Animal[] pets = { new Dog("Moti"), new Cat("Billo") };
foreach (var pet in pets)
{
    Console.WriteLine(pet.Describe());
}

abstract class Animal
{
    public string Name { get; }
    protected Animal(string name) => Name = name;
    public abstract string Sound();
    public virtual string Describe() => $"{Name} says {Sound()}";
}

class Dog : Animal
{
    public Dog(string name) : base(name) { }
    public override string Sound() => "Woof";
}

class Cat : Animal
{
    public Cat(string name) : base(name) { }
    public override string Sound() => "Meow";
    public override string Describe() => base.Describe() + " (and ignores you)";
}
Output
Moti says Woof
Billo says Meow (and ignores you)
Run this example on your own computer. The "Get Started" lesson shows how to set it up.

C# Inheritance & Polymorphism Practice Exercises

Check what you learned in “C# Inheritance & Polymorphism”.

/ 2 solved
Fill in the blank

Replace a virtual method in a child class.

public  string Sound() => "Woof";
✓ Correct! Not quite. Try again.
Multiple choice

Which keyword calls the parent class constructor?

✓ Correct! Not quite. Try again.
to save your exercise progress.
Finished this lesson?
Mark it complete to track your progress.

Stuck on something?

Ask the community in the CodesInTech forum.

Need a developer?

Learning on your own is great — and when you need professional help, our team builds custom software, websites and mobile apps for clients worldwide.

Explore Our Services