C# – Why do we need to use sealed on a class? Do we really need sealed

cnet

Reading this article (by Eric Lippert), it has four arguments as to why you should use sealed, however, I don't understand why we actually need it. Philosophical/aesthetic reasons aside, why do we need to use sealed?

I can see how things like readonly from C# or const from C++ actually catch genuine errors. Is there any type of error that sealed can catch?

An often cited reason for sealing a class is because, it hasn't been to designed to be extended. What does that mean? Why is it important? Are there any real examples of this?

The point on compatibility isn't a reason why we need to seal classes but why it should be default.

The final point again is strange, because sealing your class doesn't prevent someone providing an alternative implementation in a heirachy.

Edit:

If I didn't put enough emphasis, on it already I'm looking for reasons we actually need it. Not the usual, "someone else might write bad code". I understand that plenty of people like using sealed for design intent, but I'm looking for a practical purpose beyond that.

Best Answer

What does that mean?

It means that it is difficult for people to obey the Liskov Substitution Principle (or less likely, the Open Closed Principle) with the class as is. It has subtle, or difficult to enforce behavior that inheritors are likely to screw up. Or they're not likely to screw up, but the impact of screwing them up is huge.

The final point again is strange, because sealing your class doesn't prevent someone providing an alternative implementation.

Sure it does. If some method takes object A or some other class uses type A, by having A sealed, people cannot override it with B and then pass B into the method or use it in the class. Consumers of A can see it's sealed and know that A is the only behavior they're getting.

All that said, we don't need sealed - just like we don't need readonly. They are tools to help programmers prevent misuse, because misuse leads to bugs. Though personally, I dislike sealed; even in these days where composition over inheritence is well known, it is rare that you can say "nobody will ever need to extend this" and actually be right.

Related Topic