What is the difference between a non-virtual method and a sealed method?
Sealed methods can only be methods that override a method from the base class so no further overriding is possible.
From the docs :
When an instance method declaration includes a sealed modifier, that method is said to be a sealed method.
If an instance method declaration includes the sealed modifier, it must also include the override modifier.
This is not required for virtual methods.
sealed
prevents any further overriding of the virtual methods up the chain. You can only define sealed
on methods that are overidden. Take a look at the docs for sealed
: http://msdn.microsoft.com/en-us/library/aa645769(v=vs.71).aspx
They give a great example of sealed usage:
using System;
class A
{
public virtual void F() {
Console.WriteLine("A.F");
}
public virtual void G() {
Console.WriteLine("A.G");
}
}
class B: A
{
sealed override public void F() {
Console.WriteLine("B.F");
}
override public void G() {
Console.WriteLine("B.G");
}
}
class C: B
{
override public void G() {
Console.WriteLine("C.G");
}
}
In this case anyone who derives off of B
can override G
, but not F
.
If I read this correctly, sealed allows to stop virtual from being virtual. Essentially undoes virtual.