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.
- lets a derived (child) class replace a method; replaces it. This is run-time polymorphism: one call, different behaviour depending on the object.
- The call is dispatched (routed) on the object's run-time type, not the variable's declared type:
Contract c = new Loan()thenc.Describe()runs . - Under the hood each type has a method table, a list of its methods; an override takes the parent method's place in the child's table, so the call is one lookup, not a type check.
- It replaces type checks like if / switch on a kind: adding a new type means adding a class, not editing every switch. C# methods are not virtual by default, unlike Java.
In the lending API
Before: the if / else. After: the parent, two children and the call. Press Next line to walk through them.
What they ask next
Interviewers check that you can explain every line. Tap a question to open it.
What if the child writes without ?
The compiler warns (CS0114) and treats it as a new, separate method that only runs through a Loan-typed variable. Calls through a Contract variable still run Contract's version. That bug, and the keyword , are on .
Can the override still use the parent's code?
Yes: runs the parent's version. Example:
=> base.Describe() + ", loan";.Can you override a method that is not virtual?
No, it will not compile. In C# a method must be marked , or to be replaced. Java is the other way round: every method can be replaced unless marked final.
Overriding vs overloading?
Overriding: a child replaces a parent's method with the same signature; picked while the app runs, by the object's type. Overloading: two methods with the same name but different parameters in one class; the compiler picks one when you build, by the arguments.
Is a virtual call slower?
Only by one table lookup, which is nothing next to a database call. The JIT (the part of .NET that turns your code into machine code while it runs) can often remove even that when it knows the exact type.
Traps
- Don't say
The variable's type decides which method runs.SayThe object's run-time type decides, for virtual methods. - Don't say
Every C# method can be overridden.SayOnly , or methods. The default is not virtual.