Skip to content

1.7 — Inheritance: virtual, override, new, sealed, abstract

← Roadmap · Section: 1. C# Language Fundamentals Prev: 1.6 const, readonly, init, required · Next: 1.8 Interfaces

Markers: 🔥 ⚠️ · Confidence: 🔴 · Last reviewed: —


TL;DR

  • virtual + override = the real object decides which method runs.
  • new = the variable's declared type decides which method runs. This is almost always a bug, and it is the most-asked trap in this topic.
  • A class can inherit from only one class, but can implement many interfaces. sealed stops anyone inheriting further.

The concept

Inheritance lets one class build on another, reusing its code and changing parts of it.

Almost all the interview value here sits in one distinction: overriding versus hiding. If you understand that clearly, you have covered most of what gets asked.

Two words first:

  • Base class — the class being inherited from. Also called the parent.
  • Derived class — the class doing the inheriting. Also called the child or subclass.

How it works

virtual and override — the real object wins

virtual on a method means "a derived class is allowed to replace this". override means "here is my replacement".

The important part: C# decides which version to run by looking at what the object actually is, not what type the variable says it is.

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

public class Dog : Animal
{
    public override string Speak() => "Woof";
}
Animal a = new Dog();
// The VARIABLE says Animal.
// The OBJECT is actually a Dog.

a.Speak();   // "Woof"
// The object wins. This is polymorphism.

This is what makes inheritance useful. You can write code that works with Animal and it will automatically do the right thing for every kind of animal you create later.

new — the variable wins (the trap)

new does something completely different. It does not replace the base method. It creates a separate, unrelated method that just happens to share the name.

And this time C# decides which one to run by looking at the declared type of the variable.

public class Cat : Animal
{
    public new string Speak() => "Meow";   // 'new', not 'override'
}

Now watch the same object give two different answers:

Animal a = new Cat();
a.Speak();   // "..." — the BASE method!
// The variable is declared as Animal, so C# runs Animal's version.
// It does not care that the object is really a Cat.

Cat c = new Cat();
c.Speak();   // "Meow"
// Same kind of object. Different declared type. Different answer.

One object, two answers, depending only on how you declared the variable. That is the demonstration to have ready in an interview.

If you leave out the word new when hiding, you only get a warning, not an error. So this can happen by accident.

Practical advice: if you find yourself writing new on a method, stop. Nine times out of ten you meant override and forgot to put virtual on the base method.

So why does new exist at all? For a specific problem: imagine you write class MyList that inherits from someone else's library class, and you add a method called Sort. Later, the library authors add their own Sort. Without new, your code would suddenly break. new lets you say "I know there is a clash, mine is separate, leave me alone."

abstract — incomplete on purpose

abstract on a class means you cannot create it directly. It only exists to be inherited from.

abstract on a method means it has no body, and every derived class must provide one.

public abstract class Shape
{
    // No body. Every shape must supply its own.
    public abstract double Area();

    // A normal method with a body — every shape gets this for free.
    public string Describe() => $"Area: {Area():F2}";
}

var s = new Shape();   // ERROR — Shape is abstract, it is incomplete

Notice how Describe calls Area even though Area has no implementation here. That works because by the time the code actually runs, the object is always some real shape that has filled Area in.

That combination — some methods finished, some left for the child to fill in — is the main advantage an abstract class has over an interface.

sealed — no more inheriting

public sealed class FinalDog : Animal { }
// Nothing can inherit from FinalDog. The chain stops here.

public class Puppy : Dog
{
    public sealed override string Speak() => "Yip";
    // Puppy CAN be inherited from,
    // but no further class may override Speak() again.
}

There are two reasons to seal a class.

The design reason: you are saying "I did not design this to be extended". That protects you from a real problem where someone inherits from your class, depends on some internal detail of how it works, and then your next update breaks their code.

The performance reason: when the compiler knows nothing can override a method, it can call it directly instead of looking it up at runtime, and sometimes copy the method body straight into the caller. That is a small but free speed-up on frequently used types.

base — reaching the parent

public class Dog : Animal
{
    public Dog(string name) : base(name) { }
    // Calls Animal's constructor first, passing the name up

    public override string Speak() => base.Speak() + " Woof";
    // Runs Animal's version, then adds to it
}

Constructors run parent first, then child. And that creates a trap.

If a base constructor calls a virtual method, the derived class's override runs — but at that moment the derived constructor has not run yet. So the derived object's fields are still empty:

public class Base
{
    public Base() => Init();                    // runs FIRST
    protected virtual void Init() { }
}

public class Derived : Base
{
    private readonly List<int> _items = new();  // runs AFTER Base's constructor

    protected override void Init() => _items.Add(1);
    // CRASH! _items is still null right now.
}

Never call virtual methods from a constructor. The null reference this produces looks impossible when you are debugging it.


Code

Here is a realistic example — a shared payment flow where each provider fills in one step.

public abstract class PaymentProcessor
{
    // The shared recipe. Every processor follows these three steps in this order.
    public async Task<Receipt> ProcessAsync(Payment p, CancellationToken ct)
    {
        Validate(p);                                 // step 1 — can be customised
        var result = await ChargeAsync(p, ct);       // step 2 — MUST be supplied
        return BuildReceipt(result);                 // step 3 — always the same
    }

    // virtual: there is a sensible default, but children may add to it
    protected virtual void Validate(Payment p)
    {
        if (p.Amount <= 0)
            throw new ArgumentException("Amount must be positive");
    }

    // abstract: there is no sensible default. Every child MUST write this.
    protected abstract Task<ChargeResult> ChargeAsync(Payment p, CancellationToken ct);

    // private: nobody can change this. It is the same for everyone.
    private Receipt BuildReceipt(ChargeResult r) => new(r.TransactionId, r.Amount);
}

And a concrete implementation:

public sealed class StripeProcessor(IStripeClient client) : PaymentProcessor
{
    // Required — the base class declared this abstract
    protected override Task<ChargeResult> ChargeAsync(Payment p, CancellationToken ct)
        => client.ChargeAsync(p.Amount, p.Currency, ct);

    // Optional — we are adding an extra rule on top of the default one
    protected override void Validate(Payment p)
    {
        base.Validate(p);   // don't lose the base rule! Easy to forget.

        if (p.Currency is not ("USD" or "EUR"))
            throw new NotSupportedException($"Unsupported currency {p.Currency}");
    }
}

Two things to notice:

  • ProcessAsync is not virtual. The order of the steps is fixed. Only the individual steps can vary. This is called the Template Method pattern — see 22.5.
  • base.Validate(p) has to be written explicitly. If you forget it, you silently lose the "amount must be positive" check.

Interview questions

Q: What is the difference between override and new?

override replaces the base method, and C# decides which version to run based on what the object actually is at runtime. new does not replace anything — it declares a separate method that happens to share the name, and C# decides which to run based on the declared type of the variable. So with new, the same object gives you the base method when called through a base-typed variable and the derived method through a derived-typed variable — two different answers for one object. That is almost always a bug. new mainly exists so that a base class adding a new method later does not silently break classes that already inherit from it.

Q: When would you use an abstract class instead of an interface?

An abstract class when there is real shared code or shared state to inherit, and when the types genuinely form an "is-a" relationship — a StripeProcessor is a PaymentProcessor. An interface when you are describing a capability that unrelated types can have, or when a type needs to satisfy several contracts, because C# only allows one base class. In practice I usually define the contract as an interface so consumers depend on that, and add an abstract base class only when there is genuinely shared implementation. That way the base class is an implementation detail rather than part of the public design.

Q: Why would you seal a class?

Two reasons. Design: you are stating that this class was not built to be inherited from, which avoids the problem where someone's subclass quietly depends on internal behaviour that you then change. Performance: because the compiler knows no one can override the methods, it can call them directly rather than looking them up, and sometimes inline them. It is a reasonable default for concrete classes you did not deliberately design for extension.

Q: Can you call a virtual method from a constructor?

You can, but you should not. Constructors run from the base class down, so a virtual call in a base constructor jumps into the derived override at a point where the derived constructor has not run yet. All the derived class's fields are still null or zero, and its readonly fields are unassigned. The result is a null reference exception that looks impossible when you read the code, because the field it complains about is clearly initialised right there in the class.


Traps ⚠️

  • Writing new when you meant override. Which method runs then depends on the variable's declared type, and it only produces a warning if you leave the keyword off.
  • Calling virtual methods from a constructor. The override runs before the derived class has set up its own fields.
  • Forgetting base.Method() inside an override. The base version does not run automatically. If it did something important, you have just silently removed it.
  • C# has no multiple class inheritance. One base class only. Any number of interfaces.
  • Deep inheritance chains are a warning sign. Past two or three levels, it becomes very hard to work out where behaviour actually comes from. Composition is usually clearer — see 22.2.
  • protected members are part of your public API. Anyone inheriting from your class depends on them, so changing one is a breaking change even though it is not public.


Sources