I have read that a protected member can be accessed from derived classes, but the following does not work.
class A
{
protected int Test;
}
class B:A
{
A instanceOfA= new A()
public B()
{
instanceOfA.Test //Not possible
}
}
I have read that a protected member can be accessed from derived classes. Why my does my use of “protected” not work?
This is illegal because you have not provided a guarantee that you are accessing data of an instance of "B". Consider this similar case:
abstract class BankAccount
{
protected int accountNumber;
}
class SwissBankAccount : BankAccount
{
}
--- in another assembly, evil-doers write ---
class EvilBankAccount : BankAccount
{
void DoEvil()
{
BankAccount b = GetASwissBankAccount();
int number = b.accountNumber;
}
}
EvilBankAccount does not inherit from SwissBankAccount, so SwissBankAccount's protected member is not allowed to be used inside EvilBankAccount. You're allowed to access the protected members of your "parents", but not your "siblings"! EvilBankAccount can only access protected members of EvilBankAccount (or a type derived from EvilBankAccount). SwissBankAccount's protected members are off-limits.
The rule is that the type of the "receiver" expression that the protected instance member is accessed through has to be at least as derived as the type declaration containing the member access. For the precise wording of the rule and some illustrative examples see section 3.5.3 of the C# 4.0 specification.
Incidentally, C++ also has this rule.
This rule is frequently misunderstood. For a more in-depth analysis of this rule and some of the other consequences of protected access, see my articles on the subject. The most germane articles I've written on this subject are this one and this one. There are a bunch more articles I've written on related topics here (though some of them wander off the topic of protected access itself and onto the topic of how to use protected access to build a data model with parent references.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With