Inheritance
Inheritance in C#
Syntax
Use : to inherit from a base class:
csharp
class Dog : Animal { … }base keyword
base(args)— calls the base class constructor.base.Method()— calls the base class implementation of a method.
virtual and override
A base class marks overridable methods with virtual. Subclasses use override to provide new implementations:
csharp
public virtual string Sound() => "...";
// In subclass:
public override string Sound() => "Woof";sealed
sealed class— cannot be subclassed.sealed override— prevents further overriding of a method.
Key points:
- C# supports single class inheritance.
new(method hiding) is different fromoverride— it hides rather than overrides, breaking polymorphism.- All C# classes implicitly extend
System.Object.
Code Examples
virtual, override, basecsharp
using System;
class Animal {
public string Name { get; }
public Animal(string name) => Name = name;
public virtual string Sound() => "...";
public string Describe() => $"{Name} says {Sound()}";
}
class Dog : Animal {
public string Breed { get; }
public Dog(string name, string breed) : base(name) => Breed = breed;
public override string Sound() => "Woof";
}
class Cat : Animal {
public Cat(string name) : base(name) {}
public override string Sound() => "Meow";
}
class Program {
static void Main() {
Animal[] pets = { new Dog("Rex", "Labrador"), new Cat("Whiskers") };
foreach (var pet in pets)
Console.WriteLine(pet.Describe());
}
}virtual/override enables runtime polymorphism. The correct Sound() is called based on the actual object type, not the variable type.
Quick Quiz
1. What is the difference between `new` and `override` on a method?
2. What does `sealed class` mean in C#?
Was this lesson helpful?