Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this C# class declaration compile?

Tags:

c#

.net

sealed

This question really is kinda pointless, but I'm just curious:

This:

public sealed class MyClass
{
   protected void MyMethod(){}
}

compiles, but gives a warning

while This:

public sealed class MyClass
{
   public virtual void MyMethod(){}
}

doesn't compile. Just out of sheer curiosity, is there a reason for this?

like image 632
BFree Avatar asked Jul 21 '09 02:07

BFree


1 Answers

virtual is used to declare a method/property "override-able".

sealed is used to declare that class cannot be inherited from.

So a virtual method in a sealed class could never be overridden, as the class could never be inherited from. It just doesn't make sense.

protected affects access to a member, it does not declare it "override-able" as virtual does (though it is often used in that manner) and is accordingly not contradictory.

like image 75
Kevin Montrose Avatar answered Oct 28 '22 20:10

Kevin Montrose