Reputation: 225
I am trying to access protected member variables in different ways in the child class. I found I can not do so by using object reference of child class to parent class object. Here I am referring to "int Number6" in the following program.
However I can access "int Number7" which is public. I want to know the reason behind this.
public class Customer
{
#region Fields
protected int Number2;
protected int Number3;
protected int Number4;
protected int Number5;
protected int Number6;
public int Number7;
#endregion
}
public class CorporateCustomer : Customer
{
public void PrintID()
{
CorporateCustomer CC = new CorporateCustomer();
CC.Number2 = 101;
base.Number3 = 103;
this.Number4 = 104;
Customer C2 = new CorporateCustomer();
C2.Number6 = 106; //-> Not Possible to access protected Number6 by this way
C2.Number7 = 105; //-> However, can access public field
}
}
Upvotes: 2
Views: 2375
Reputation: 3307
Interesting question - the msdn states that this won't work:
A protected member of a base class is accessible in a derived class only if the access occurs through the derived class type.
Since you are using the basetype instead of the derived type, consequently this does not work.
But why? I could imagine that this relates to the issue that a Customer could also be derived by another class than CorporateCustomer. In this case the instance that you assigned to Customer would not necessarily be a CorporateCustomer and so the protected attribute correctly forbids to access the Number6 property because it would break the accessibility restriction.
public class PrivateCustomer : Customer
{
}
public class CorporateCustomer : Customer
{
public void PrintID()
{
Customer C = new PrivateCustomer();
C.Number6 = 106; //-> Not Possible to access protected Number6 by this way which is alright, as this is not a Corporate Customer
C.Number7 = 105; //-> However, can access public field
}
}
The C# Language Specification states exactly this example as a reason this doesn't work:
3.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 must take place within a class declaration that derives from the class in which it is declared. Furthermore, the access is required to take place through an instance of that derived class type or a class type constructed from it. This restriction prevents one derived class from accessing protected members of other derived classes, even when the members are inherited from the same base class.
Upvotes: 2