← Foundations path
.NETFoundations 8 / 37

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 .

Say it in the interview

In the lending API

Sealing Loan, then the hiding bug and its fix. Press Next line to walk through them.

Diagram · step 3The fix: sealed class Loan. Now : Loan fails to build (error CS0509).
Loan.cs · line 1 · 1 of 2: Loan can still inherit from Contract, but nothing can inherit from Loan.

What they ask next

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

Traps

Read more: Microsoft Learn: sealed · new modifier · Knowing when to use override and new