0 votes
by (2.5k points)
edited by
I got asked in a job interview what a "sealed" class is. I looked it up after and it was easy but.. I'm not sure where I would use it?

1 Answer

0 votes
by (2.5k points)

As you've already noted, a sealed class is actually relatively simple to understand. You can simply mark a class as sealed : 

sealed class MyClass
{
}

And this just means that no class can then inherit from it : 

class MySecondClass : MyClass //Compiler error
{
}

Easy right!

But as for the second part of your question, where would you actually use it? If you are looking to really lock down a class and make sure it can't be overriden in any way (So the functionality is always the same), for example if you are building a C# library, you may wish to seal it. 

In saying that, if you scroll through the .NET Github repositories, you will find countless examples of users complaining that a particular class is sealed for no good reason and can it be unsealed. If anything, you'll probably run into more cases where you'll be asked to unseal a class than times where you wish you had sealed it. 

Welcome to .NET Q&A, where you can ask questions and receive answers from other members of the community.
...