ECMA-334: 10.5.3 Protected access for instance members
Microsoft .NET Framework, ASP.NET, Visual C# (CSharp, C Sharp, C-Sharp) Developer Training, Visual Studio
| C# Language Specification |
|
| © 2006 ECMA International |
10.5.3 Protected access for instance members
When a protected instance member is accessed outside the program text of the class in which it is
declared, and when a protected internal instance member is accessed outside the program text of the
program in which it is declared, the access is required to take place through an instance of the derived class
type in which the access occurs. Let B be a base class that declares a protected instance 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:
- An unqualified type-name or primary-expression of the form
M.
- A primary-expression of the form
E.M, provided the type ofEisDor a class derived fromD.
- A primary-expression of the form base
.M.
In addition to these forms of access, a derived class can access a protected instance constructor of a base class in a constructor-initializer (§17.10.1).
[Example: In the following code
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. end example]
In the context of generics (§25.1.6), the rules for accessing protected and protected internal
instance members are augmented by the following:
- Within a generic class
G, access to an inherited protected instance memberMusing a primary-expression of the formE.Mis permitted if the type ofEis a class type constructed fromGor a class type derived from a class type constructed fromG.