Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In this case, is the compiler REALLY forcing me to use protected in a sealed class?

Tags:

c#

inheritance

I can't think of an instance where a protected method should behave differently than a private method in a sealed class.

And yet:

public abstract class Base
{
    protected abstract void Foo();
}

public sealed class Derived : Base
{
    // Error CS0507: cannot change access modifiers when 
    // overriding 'protected' inherited member
    // public override void Foo() {}

    // Error CS0621: virtual or abstract members cannot be private
    // private override void Foo() {}

    // Compiles just fine.
    protected override void Foo() {} 
}
like image 421
Zaaier Avatar asked Feb 26 '14 23:02

Zaaier


2 Answers

In this case the compiler is faced with two seemingly odd choices

  1. private override which is a bit non-sensical because virtual methods should never be private
  2. protected override which is a bit non-sensical because protected methods should never be declared in a sealed type

Option #1 would be a bit odd because it's taking something which is an error everywhere else (private virtual) and making it a non-error in this specific case. Option #2 though requires no special rules in the compiler. It's always legal to declare a protected member in a sealed type just a bit odd to do so (issues a warning). Hence the compiler has chosen the lesser of two odd syntaxes

like image 187
JaredPar Avatar answered Oct 21 '22 14:10

JaredPar


The compiler isn't really "forcing" you to use protected. It was defined as protected, and will always be protected.

Even though it is in a sealed class, it is still not like a private member. If it were private, it would not be accessible from the base class.

like image 32
Seattle Leonard Avatar answered Oct 21 '22 13:10

Seattle Leonard