Sparkette
Sparkette

Reputation: 1869

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.

Upvotes: 6

Views: 2596

Answers (3)

Jay
Jay

Reputation: 57959

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

Upvotes: 6

TGH
TGH

Reputation: 39268

I personally don't benefit much from sealed classes, and agree, it can be frustrating when dealing with UI classes and want to just add some custom behavior through inheritance. However, I found an answer here that offers a few ideas.

Why seal a class?

Upvotes: 0

Mark Sowul
Mark Sowul

Reputation: 10610

Consider

class A
{
  public virtual void M1();
  public void M2();
}

class B : A
{
  public override sealed void M1();
}

sealed class C : A
{
   //other stuff    
}

class D : A
{
   public new void M2(); //marking A as sealed would prevent this 
}

See also: Do sealed classes really offer performance Benefits? (JITter can optimize certain calls when it knows there can be no subclass)

Upvotes: 1

Related Questions