Why Sealing C# Classes by Default Makes for Safer, More Predictable Code
A software design principle gaining attention among C# developers argues that classes should be sealed by default, with inheritance only enabled when explicitly intended. An unsealed class with virtual methods acts as an implicit contract, allowing subclasses to override behavior in ways that can silently break core invariants. A practical example demonstrates how a BankAccount class with a virtual Withdraw method can be subclassed to bypass balance checks, producing incorrect negative balances with no compile-time warning. Marking the class as sealed causes the compiler to immediately flag any inheritance attempt or misplaced virtual member as an error, catching the problem before runtime. The recommendation is to treat sealing as the default stance and only open a class to inheritance when the design explicitly calls for it.
This is an AI-generated summary. ShortSingh links to the original source for the complete article.
Discussion (0)
Log in to join the discussion and vote.
Log in