๐Ÿ  VisualStudioTutor.com  ยท  C# Tutorial Home  ยท  C# Lesson 6 of 40
Lesson 6 of 40 OOP Intermediate โฑ 35 min

Inheritance & Polymorphism

Model real-world hierarchies with class inheritance, method overriding, virtual/abstract methods, sealed classes, and runtime polymorphism.

Part 1: Base & Derived Classes

public class Animal
{
    public string Name { get; }
    public Animal(string name) => Name = name;
    public virtual string Speak() => "...";
}

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

Part 2: Abstract Classes

public abstract class Shape
{
    public abstract double Area(); // Must override
    public virtual string Describe() => // May override
        $"A shape with area {Area():F2}";
}

public class Circle(double radius) : Shape // Primary ctor
{
    public override double Area() => Math.PI * radius * radius;
}

Part 3: Polymorphism in Action

List<Animal> animals = [new Dog("Rex"), new Cat("Whiskers")];
foreach (var a in animals)
    Console.WriteLine($"{a.Name}: {a.Speak()}");
// Rex: Woof!
// Whiskers: Meow!
At runtime, the correct Speak() override is called โ€” this is dynamic dispatch.

Part 4: sealed Classes & Methods

// sealed class โ€” cannot be inherited
public sealed class FinalClass {}

// sealed override โ€” stop further overriding
public class GoldenRetriever : Dog
{
    public sealed override string Speak() => "Bark!";
}
Sealing improves JIT performance โ€” the compiler can de-virtualize the call.

C# in Visual Studio 2026

๐Ÿ“˜ This lesson is part of the book C# in Visual Studio 2026 by Dr. Liew Voon Kiong.

View on Amazon Kindle Edition