Why can’t I access C# protected members except like this?

The reason this doesn’t work is because C# doesn’t allow cross-hierarchy calling of protected methods. Say there was a class E that also derived from C:

  C
 / \
D   E

Then the reference you’re trying to call the method on could actually be an instance of type E and thus the method could resolve at runtime to E.F. This is not permitted in C# as D cannot call E‘s protected methods, because E is in another branch of the hierarchy, i.e.

var d = new D();
var e = new E();
d.G(e); // oops, now this will call E.F which isn't allowed from D

This makes sense because the keyword protected means the member “is accessible within its class and by derived class instances” and E.F is not a member of D.

Leave a Comment