virtual, override and polymorphism

virtual and override

A method marked virtual may be replaced by a subclass with override, and a call through a base reference then runs the version of the object, not the version of the reference. That is polymorphism: one call site, many behaviours, chosen by the runtime type.

Animal[] animals = { new Cat("Mochi"), new Dog("Rex") }; foreach (var animal in animals) { Console.WriteLine(animal.Speak()); } Console.WriteLine($"count: {animals.Length}"); abstract class Animal(string name) { public string Name { get; } = name; public abstract string Speak(); } class Cat(string name) : Animal(name) { public override string Speak() => $"{Name} says meow"; } class Dog(string name) : Animal(name) { public override string Speak() => $"{Name} says woof"; }

dotnet run

Mochi says meow
Rex says woof
count: 2

The loop has one call, animal.Speak(), and two implementations ran. An abstract member is virtual by definition, which is why the previous lesson did not need the keyword; a normal method that subclasses may change is marked virtual and keeps a body in the base.

new hides instead of overriding

A subclass that declares a method with the same name and no override does not replace the base method; it hides it. The compiler accepts it with a warning, and the call through the base reference still runs the base version:

Base overridden = new Derived(); Base hidden = new Hider(); Console.WriteLine($"overridden through base: {overridden.Who()}"); Console.WriteLine($"hidden through base: {hidden.Who()}"); Console.WriteLine($"hidden through its own type: {((Hider)hidden).Who()}"); class Base { public virtual string Who() => "base"; } class Derived : Base { public override string Who() => "derived"; } class Hider : Base { public new string Who() => "hider"; }

dotnet run

overridden through base: derived
hidden through base: base
hidden through its own type: hider

Three lines, two answers that look inconsistent until the rule is clear: dispatch works on the runtime type only when the base member is virtual and the derived one overrides it. new is a promise that the name now means two methods, and the reference decides which one the compiler picks.

new is written out on purpose here. Without the keyword the compiler still hides the method but prints warning CS0108, which is the warning that tells a reader the hiding was not intended.

ToString and the object method

Every type derives from System.Object, and its three everyday members are virtual: ToString, Equals and GetHashCode. An array of object can hold values of any type, and Console.WriteLine calls the override of each:

object[] items = { new Money(10m), new Money(2.5m), "text", 42 }; foreach (var item in items) { Console.WriteLine(item); } Console.WriteLine($"types: {items.Length}"); record Money(decimal Amount) { public override string ToString() => $"{Amount:F2}"; }

dotnet run

10.00
2.50
text
42
types: 4

Console.WriteLine(item) takes an object and calls ToString on it, so the record printed with two decimals and the integer printed itself. The int was boxed into an object for the array, which is the cost the lesson on boxing measures.

Rules of dispatch

Exercises

  1. Make Animal.Speak virtual with a body that returns the name and nothing else, and keep both overrides.
  2. Remove new from Hider.Who and read the warning.
  3. Add a third level below Derived that overrides Who again and call all three through a Base array.
  4. Override ToString on Cat and print a cat directly, without Speak.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What decides which override of a virtual method runs?

    Answer

    The runtime type of the object

    A virtual call is dispatched on the object, which is the point of overriding.

  2. What does the new keyword on a method do?

    Answer

    Hides the base method instead of overriding it

    new starts a second method with the same name, and the reference type decides which is called.

  3. What does this program print? B b = new D(); Console.WriteLine(b.M()); class B { public virtual string M() => "b"; } class D : B { public override string M() => "d"; }

    Answer

    d

    The base member is virtual and D overrides it, so the call reaches the override.

  4. Which member of System.Object is virtual?

    Answer

    ToString

    ToString, Equals and GetHashCode are virtual; GetType is not and cannot be overridden.

  5. What does Console.WriteLine(item) do with an object?

    Answer

    Calls ToString on the runtime type

    The object overload of WriteLine calls ToString, which is why an override changes the line.

  6. What does this program print? B b = new H(); Console.WriteLine(b.M()); class B { public string M() => "b"; } class H : B { public new string M() => "h"; }

    Answer

    b

    The base method is not virtual, so the call through B is bound to it at compile time.

  7. What is required to override a method?

    Answer

    The base method must be virtual, abstract or override

    Only a virtual slot can be replaced; a plain method can only be hidden.

  8. What does this program print? object[] a = { 1, "x" }; foreach (var o in a) Console.WriteLine(o.GetType().Name);

    Answer

    Int32 and then String

    GetType reports the runtime type of each element, even boxed in an object array.

  9. Why is a virtual call slightly slower than a non-virtual one?

    Answer

    The method is looked up in the object type at run time

    Dispatch reads the method table of the runtime type instead of using a fixed address.

  10. A subclass declares public string M() where the base has public virtual string M(). What happens?

    Answer

    It hides the base method, with warning CS0108

    Without override the compiler assumes hiding and warns unless new is written.

The code on this page was built with the .NET SDK 10.0.303 and run on Alpine Linux 3.24.3 (x86_64) in a Docker container.

Article author: Arthur Isaev