If a class doesn't have any virtual methods, I do not see any way inheriting a class would affect any code that doesn't explicitly refer to the instance as an instance of the subclass i.e.
Subclass obj = new Subclass()
rather than
BaseClass obj = new SubClass()
So therefore, why does sealed
even exist?
If you're not declaring anything as virtual
(which I see no point in doing in a sealed class) all it prevents is things like (for example) a ListViewItem
that stores some extra information about what it represents for code that "knows" that information is there, which has no impact on code that wasn't written with that subclass in mind, unlike an overridden method.
sealed (C# Reference) You can also use the sealed modifier on a method or property that overrides a virtual method or property in a base class. This enables you to allow classes to derive from your class and prevent them from overriding specific virtual methods or properties.
By using sealed class, we can restrict access to the classes and its members with the help of a sealed keyword and we can also avoid inheriting the defined classes from other classes. In C#, a sealed class is a class that cannot be inherited by another class but it can be instantiated.
String is sealed mainly because it is immutable and CLR widely uses that feature (interning, cross-domain marshaling). If string would not be sealed then all CLR expectations on string immutability would not cost a dime.
Sealing a class means that you cannot use it as a superclass. Making a class static makes them useless as base classes, because they cannot have overridable methods.
(1) Sealed class
I may have a method that accepts an object of type BankAccount
. I don't want you to be able to create EvilBankAccount : BankAccount
and pass it into my method. EvilBankAccount
could potentially break my system which makes assumptions about a BankAccount
-- for example, that it can be serialized. Maybe I clone BankAccount
to prevent external manipulation once it is submitted, and EvilBankAccount
clones just fine, but starts a timer in its constructor that auto-increments the balance every 30 seconds.
(2) Sealed member
You can override a virtual method or property, but seal it so that it cannot be overridden further in the inheritance hierarchy. One use case here is when you need to access the member from your constructor.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With