← Foundations path
.NETFoundations 6 / 37

Virtual and override

“What do virtual and override do, and how does .NET pick which method runs?”

A parent says "children may replace this method"; a child replaces it. While the app runs, the object's real type decides which one runs.

See it

1/9Before. Each contract carries a Kind text. Billing reads it and picks the letter with if / else.

In plain words

on a parent's method means "a child may replace this". on the child's method replaces it. A variable can have the parent's type while the object it points to is a child. When you call the method, .NET looks at the object, not the variable, and runs that object's version. So one line of code does the right thing for every kind of contract.

Say it in the interview

In the lending API

Before: the if / else. After: the parent, two children and the call. Press Next line to walk through them.

Diagram · step 1Before. Each contract carries a Kind text. Billing reads it and picks the letter with if / else.
Before · BillingRun.cs · line 2 · 1 of 2The caller checks the type itself. Every place that needs per-type behaviour repeats this check.

What they ask next

Interviewers check that you can explain every line. Tap a question to open it.

Traps

Read more: Microsoft Learn: polymorphism · virtual keyword · override keyword