Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the purpose of "sealed" in C# when "virtual" is optional?

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.

like image 210
flarn2006 Avatar asked Mar 14 '14 01:03

flarn2006


People also ask

What is the use of sealed 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.

What is the advantage of sealed class?

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.

Why string is sealed?

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.

Why static class are sealed?

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 Answers

(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.

like image 70
Jay Avatar answered Oct 31 '22 03:10

Jay