Skip to content
Tutorials Center
My learning

Topics

Lesson 60 of 182 ยท Classes and Objects

Polymorphism: virtual, override and new

Learn C# polymorphism - virtual and override methods, dynamic dispatch, calling base, abstract members, covariant returns and the new keyword hiding trap, with runnable examples.

Polymorphism means "many forms". In C# it is the ability to write code against a general type, such as Shape, and have the right specific behavior happen at run time, depending on the actual object: a Circle computes its area one way, a Rectangle another. The calling code does not contain an if (shape is Circle) ... else if ... ladder. It just says shape.Area().

This is the payoff of inheritance. It lets you add a new kind of shape later without touching the code that processes shapes. To make it work you need three keywords: virtual (a method may be replaced), override (this method replaces the base version) and, as a trap to understand and avoid, new (hide instead of replace). This lesson explains how the runtime decides which method to call, how to extend rather than replace behavior with base, and the difference between overriding and hiding that causes real bugs.

virtual and override

A method is non-virtual by default in C#: the compiler binds the call to a fixed method at compile time. Mark it virtual in the base class to allow derived classes to replace it, and write override in the derived class to do so.

C# Virtual dispatch with shapes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The loop only knows Shape, yet each iteration calls a different Area. This is dynamic dispatch (also called late binding): the runtime looks at the object's actual type, finds the most derived override and calls it. Square overrides only Name and inherits Rectangle's Area. Adding a Triangle class later requires no change to the loop.

How dispatch works, in plain words

Every object carries a hidden pointer to its type's method table. For each virtual method, the table holds the address of the version that applies to that type. A virtual call reads the object's table and jumps through the slot. It costs one extra indirection compared with a normal call, which is tiny; the JIT can even remove it when it can prove the exact type (for example with a sealed class).

The rules

  • override requires a matching virtual, abstract or already-override method in a base class with the same signature (name, parameter types, accessibility).
  • Only virtual members can be overridden. Methods, properties, indexers and events can all be virtual; fields cannot.
  • override is implicitly virtual, so the chain continues for further subclasses unless you write sealed override.
  • Static methods and constructors cannot be virtual.

If you forget override, you get a warning that turns out to be one of the most important in the language, covered below.

Extending with base

An override does not have to discard the base version. Call it through the base keyword, then add behavior before or after:

C# Calling base.Method()

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Use base.Render() when the derived class adds to the behavior, and leave it out when it fully replaces it. A common design mistake is overriding a method and forgetting the base call that did required bookkeeping (for example raising an event or validating state). Document in the base class whether overriders must call the base version.

Overriding ToString

Every class inherits ToString() from object. By default it returns the type name, which is rarely useful. Overriding it is the most common polymorphism you will write, because Console.WriteLine, string interpolation and the debugger all call it.

C# A useful ToString

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

new Plain() prints just Plain (the type name). See The object Class for Equals and GetHashCode, which you override as a pair.

Abstract members: a promise without a body

Sometimes the base class cannot offer any sensible default. What is the area of a generic "shape"? Mark the method abstract instead of virtual: it has no body, the class must be abstract too, and every concrete subclass must override it.

C# An abstract method forces every subclass to answer

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

You cannot write new Employee("x"): an abstract class is incomplete by design. When to prefer an abstract class over an interface is the topic of Abstract Classes and Interfaces.

The trap: new hides, override replaces

What happens if a derived class declares a method with the same name as a non-virtual (or virtual) base method but without override? The compiler warns, and the new method hides the inherited one. Hiding is decided by the variable's declared type, not the object, so the polymorphism you expected silently disappears.

C# Hiding versus overriding

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The same object gives two answers depending on which variable type you look through. Anyone holding a Base reference gets Base.Hidden, which is almost never what the author of Derived intended.

Now see what the compiler says when you hide something by accident, leaving out both override and new:

C# Accidental hiding warning (warning on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The compiler prints warning CS0114: 'Child.Speak()' hides inherited member 'Parent.Speak()'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword. The program still runs and prints child. Treat this warning as an error: it means you forgot override or you are hiding on purpose and should say new explicitly.

When is new legitimate?

Almost only when you inherit from a class you do not control and a later version of it adds a member whose name collides with yours. Writing new documents the choice and silences the warning. In your own hierarchies, make the base method virtual and use override instead.

Covariant return types

Since C# 9 an override may return a more derived type than the base method. This removes casts when you clone or create objects in a hierarchy.

C# Covariant return types (C# 9)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The override's return type may be narrower; parameter types must still match exactly. This works for methods and read-only properties.

Sealing and performance notes

  • sealed override ends the override chain at one level: public sealed override double Area() => ....
  • A sealed class makes every call on it non-polymorphic, which lets the JIT inline. Prefer sealed for leaf classes unless you expect subclasses.
  • Virtual calls cannot be inlined across the virtual boundary in the general case. In tight loops over millions of items, a virtual call per element can matter; in everyday code it does not. Do not avoid virtual out of performance fear. Avoid it because every virtual member is a design commitment you have to maintain.
  • Make members virtual only if you have a concrete reason, and say in documentation how overriders should behave. Non-virtual by default (the C# choice) is deliberate: a method that was never designed for replacement is easier to keep correct.

Do not call virtual methods from constructors. The override may run before the derived class has initialized its own fields. Inheritance shows the exact failure.

Polymorphism without inheritance

Inheritance is one source of polymorphism. Interfaces (the same call on unrelated classes), delegates and generics provide others. Prefer interfaces when unrelated types share a capability, as you will see in Abstract Classes and Interfaces.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What decides which Area() runs in a loop over Shape variables when Area is virtual and overridden?

    Virtual calls use dynamic dispatch: the runtime looks at the object's real type and calls the most derived override.
  2. 2. A derived class declares public string Speak() with the same signature as a virtual base method, with no override and no new. What happens?

    Without override the method hides the base one. The compiler warns (CS0114) and a call through a base-typed variable still runs the base version.
  3. 3. Which is true of an abstract method?

    An abstract method has no implementation; the declaring class must be abstract, and non-abstract subclasses must override it.
  4. 4. What does base.Render() do inside an override?

    base.Method() calls the version from the base class, which lets an override extend instead of replace.
  5. 5. What do covariant return types (C# 9) allow?

    An override may narrow the return type, for example Dog Clone() overriding Animal Clone(), so callers need no cast.

Summary

  • virtual allows replacement, override replaces, and calls are resolved at run time by the object's actual type.
  • Use base.Method() to extend instead of replace; abstract members force subclasses to supply behavior.
  • Override ToString() on your types for readable output and debugging.
  • new hides rather than overrides; the call then depends on the variable's declared type. Treat CS0114 as a bug signal.
  • Covariant returns (C# 9) let overrides return a narrower type; sealed override stops further overriding.
  • Make members virtual only when you design for it; prefer sealed leaf classes.

Next: Abstract Classes and Interfaces