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() {}
}
In this case the compiler is faced with two seemingly odd choices
private override
which is a bit non-sensical because virtual methods should never be private 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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With