Lesson 15 of 24

In progress

Course progress

C# and .NET

Inheritance and polymorphism

Extend a class with virtual and override, call base members, and know when composition is the safer design.

C# inheritance is explicit: a method must be declared virtual before a subclass can override it. That single rule prevents the accidental overriding that makes inheritance risky in other languages.

What you will learn

  • Declare virtual methods and override them.
  • Use base to call the parent version.
  • Tell new from override, and prefer composition.

Extending

public class Account
{
public decimal Balance { get; protected set; }
public Account(decimal opening) => Balance = opening;
public virtual string Describe() => $"Account with {Balance:F2}";
}
public class SavingsAccount : Account
{
public int InterestBps { get; }
public SavingsAccount(decimal opening, int interestBps) : base(opening)
{
InterestBps = interestBps;
}
public override string Describe() =>
$"Savings at {InterestBps} bps, {base.Describe()}";
}

SavingsAccount calls base(opening) to initialise the parent, then adds its own field. override replaces Describe, and base.Describe() reuses the parent’s text.

A method that is not virtual cannot be overridden. That is a deliberate design choice: the author of the base class decides which parts are extension points, and everything else is fixed.

What is inherited

Public and protected members are inherited. Private members exist in the object but are not accessible to the subclass, which is why Balance uses protected set: the subclass can adjust it, but outside code cannot.

protected is the loosest sane level. A protected field exposes state to every subclass and its future changes; a protected method or property with validation is usually better.

Hiding versus overriding

public class Base
{
public virtual void Show() => Console.WriteLine("base");
}
public class Overrider : Base
{
public override void Show() => Console.WriteLine("overrider");
}
public class Hider : Base
{
public new void Show() => Console.WriteLine("hider");
}

Through a Base reference, Overrider.Show() runs the override and Hider.Show() runs the base method, because new creates a separate method rather than replacing one. Hiding is almost always a mistake: it makes behaviour depend on the variable’s static type, and the compiler warns about it unless new is written.

Polymorphism

var accounts = new List<Account>
{
new Account(100m),
new SavingsAccount(500m, 400)
};
foreach (var account in accounts)
{
Console.WriteLine(account.Describe());
}

The list holds Account references, and each call runs the object’s own implementation. That is the payoff: code written against the base type works for every subclass, including ones added later.

The substitution must be honest. If a subclass throws where the parent promises a value, or ignores a parameter that changes the meaning, the hierarchy is wrong. That is the Liskov substitution principle, and violating it produces bugs that no compiler catches.

Abstract classes

public abstract class Shape
{
public abstract double Area();
public virtual string Name => GetType().Name;
}

An abstract class cannot be instantiated and may declare abstract members that subclasses must implement. It can also hold state and concrete methods, which an interface cannot.

public sealed class Circle : Shape
{
private readonly double radius;
public Circle(double radius) => this.radius = radius;
public override double Area() => Math.PI * radius * radius;
}

sealed on Circle stops further inheritance. Sealing a leaf class makes its behaviour predictable and lets the runtime devirtualise calls.

Composition first

public class SavingsAccount
{
private readonly Account account;
private readonly int interestBps;
public SavingsAccount(Account account, int interestBps)
{
this.account = account;
this.interestBps = interestBps;
}
public decimal Balance => account.Balance;
public void Deposit(decimal amount) => account.Deposit(amount);
}

Delegation costs a few forwarding members and buys independence from the parent’s internals. A change to Account no longer breaks SavingsAccount unless the contract changes.

Use inheritance when the subtype genuinely is a kind of the parent and behaves the same way under every operation the parent promises. Otherwise, hold the object.

Constructor order

Parent constructor, then field initialisers of the child, then the child’s constructor body. That order explains why calling an overridable method from a constructor is dangerous: the override runs before the child’s fields are set.

When not to use inheritance

  • To share a couple of helpers: a static class or a utility method is simpler.
  • To model a role that changes at runtime: composition or an interface fits better.
  • Because the base class is convenient: that couples two unrelated concepts forever.

A hierarchy that exists only to reuse two methods costs more than the duplication it removes, because every change to the parent becomes a change to every child. Duplication is cheaper to fix than a wrong abstraction, so prefer the duplication until the shared shape is clear.

Declaring a method override when the base method is not virtual. The compiler rejects it, which is the useful outcome; the dangerous version is forgetting override and hiding the method instead.

Create an abstract Shape with Area() and Describe(), then a Rectangle and a Circle, and print descriptions through a List<Shape>.

Show solution
public abstract class Shape { public abstract double Area(); public virtual string Describe() => $"{GetType().Name} with area {Area():F2}"; } public sealed class Rectangle : Shape { private readonly double w, h; public Rectangle(double w, double h) => (this.w, this.h) = (w, h); public override double Area() => w * h; } public sealed class Circle : Shape { private readonly double r; public Circle(double r) => this.r = r; public override double Area() => Math.PI * r * r; } foreach (var shape in new List<Shape> { new Rectangle(2, 3), new Circle(2) }) { Console.WriteLine(shape.Describe()); }

Describe is written once in the base class and calls the abstract Area, so each subclass supplies only what differs. Sealing the leaves makes the set of shapes closed and the behaviour easy to reason about.

Recap

  • A method must be virtual to be overridden; base calls the parent version.
  • new hides a method instead of overriding it and should be avoided.
  • Prefer composition unless the subtype genuinely is the parent under its whole contract.

Next, interfaces: contracts, default implementations and the pattern that replaces inheritance.

Can a class inherit from several classes?
No. It can implement several interfaces, which is how multiple types are expressed.
Can a constructor be virtual?
No. Constructors are not inherited, so they cannot be overridden.

Progress is saved in this browser only. No account, no email.

Admin

About the author

Admin

Instructor and technical writer at tutorials.in

Writes beginner lessons for tutorials.in. Each lesson is checked against the language or tool documentation, and examples are run before publishing.

Reviewed by the editorial team before publishing. Last updated November 16, 2026.