C# VS2026
Lesson 17 of 30

OOP – Inheritance and Polymorphism

C# in Visual Studio 2026 — a hands-on guide for developers at every level.

Inheritance

A derived class inherits all public and protected members of its base class and can add or override behaviour.

public class Animal
{
    public string Name { get; }
    public Animal(string name) => Name = name;
    public virtual string Speak() => "...";
    public override string ToString() => $"{Name} says: {Speak()}";
}

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

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

Animal[] animals = { new Dog("Rex"), new Cat("Whiskers") };
foreach (var a in animals)
    Console.WriteLine(a);
// Rex says: Woof!
// Whiskers says: Meow!

sealed Classes

Marking a class sealed prevents any further inheritance:

public sealed class Singleton
{
    public static readonly Singleton Instance = new();
    private Singleton() { }
}

Type Checking and Casting

Animal a = new Dog("Buddy");

if (a is Dog dog)
    Console.WriteLine($"{dog.Name} is a dog");

Dog? d = a as Dog;  // null if cast fails