As explained in this question, and these articles, the following is not allowed:
public class A
{
protected virtual int X {get; private set;}
}
public class B : A
{
public int Add(A other)
{
return X + other.X;
}
}
Because if it was, and you had this:
public class C : A
{
protected override int X { get { return 4; } }
}
and then:
A c = new C();
B b = new B();
b.Add(c);
This is illegal because even though B
's access to X
means it knows that C
has the desired signature it's still not allowed to actually access the member.
So far, so good. But given the above, what I'm confused about is why I can do this:
public class A
{
protected virtual int X { get; private set; }
public int Add(A other)
{
return X + other.X;
}
}
And, therefore, this:
A c = new C();
A a = new A();
a.Add(c);
The definition of the protected keyword says:
A protected member is accessible within its class and by derived class instances.
But now the protected member on C
is being accessed from within A
, which is neither "its class" nor a "derived class instance", but a parent class. While A
obviously has access to the signature, the sibling example seems to indicate that that alone is not supposed to be sufficent, so why is protected
granting it access to the member?