Sealed, and the two meanings of new
“What does sealed do, and what is the difference between new and override on a method?”
`sealed` stops anyone inheriting from a class. `new` builds an object, but on a method it hides the parent's one, which causes a classic bug.
See it
1/9Before. Anyone can write class CarLoan : Loan and override Loan's methods.
In plain words
on a class means nothing may inherit from it, so nobody can change how it behaves by overriding. The word has two jobs. new Loan(...) builds an object. written on a method says "this is a different method that happens to share the parent's name": it hides the parent's method instead of replacing it. Calls through a parent-typed variable then still run the parent's code, which is almost never what you wanted. Use .
- prevents inheritance (error CS0509 if you try). I seal classes that were not designed to be extended; it also lets .NET skip the virtual method lookup.
- as an operator creates an instance. as a modifier hides a base member: method hiding.
- With hiding, the method is chosen by the variable's declared type, when you build; with , by the object's real type, while the app runs. So through a base-type variable a hidden method never runs.
- Leaving out both keywords gives warning CS0114 and hides by default. I treat that warning as an error in the build.
In the lending API
Sealing Loan, then the hiding bug and its fix. Press Next line to walk through them.
sealed class Loan. Now : Loan fails to build (error CS0509).What they ask next
Interviewers check that you can explain every line. Tap a question to open it.
Why would you ever want method hiding?
Almost never on purpose. It exists for a library upgrade case: the parent class adds a method with a name your child class already had. tells the compiler "yes, I know, keep mine separate" and silences the warning.
Can you seal just one method?
Yes:
public sealed override string Describe()in a child stops grandchildren from overriding it further. Only works on a method that is itself an override.Why seal by default?
A class that allows inheritance must be designed for it: which methods are safe to replace, in what order they run. If you did not design that, seal it. Unsealing later is easy; sealing later breaks anyone who inherited. .NET also runs slightly faster when it knows no override can exist.
Static class and sealed?
A is sealed and abstract at once under the hood: nobody can build it and nobody can inherit from it.
How do you stop the hiding bug from shipping?
Turn warnings into errors for CS0114 and CS0108 in the project file, so the build fails. Code review catches the rest: on a method should always need a comment saying why.
Traps
- Don't say
on a method creates a new object.SayOn a method, hides the parent's method. It creates nothing. - Don't say
and both replace the parent's method.SayOnly does. adds a second method that runs only through the child's type.