When a protected
member is accessed outside the program text of the class in which it is declared, and when a protected
internal
member is accessed outside the program text of the project in which it is declared, the access is required to take place through the derived class type in which the access occurs. Let B
be a base class that declares a protected member M
, and let D
be a class that derives from B
. Within the class-body of D
, access to M
can take one of the following forms:
M
.T.M
, provided T
is D
or a class derived from D
.E.M
, provided the type of E
is D
or a class derived from D
.base.M
.In addition to these forms of access, a derived class can access a protected constructor of a base class in a constructor-initializer (§10.10.1).
In the example
public class A { protected int x; static void F(A a, B b) { a.x = 1; // Ok b.x = 1; // Ok } } public class B: A { static void F(A a, B b) { a.x = 1; // Error, must access through instance of B b.x = 1; // Ok } }
within A
, it is possible to access x
through instances of both A
and B
, since in either case the access takes place through an instance of A
or a class derived from A
. However, within B, it is not possible to access x through an instance of A, since A does not derive from B.