I read that a protected member can be accessed from derived classes. Why is my use of “protected” not working?
This is illegal because you have not made a guarantee that you are accessing instance B data. 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, therefore a protected member of SwissBankAccount is not allowed to be used inside EvilBankAccount. You can access the protected members of your "parents", but not your "brothers and sisters"! EvilBankAccount can only access protected members of EvilBankAccount (or a type obtained from EvilBankAccount). SwissBankAccount protected members have no restrictions.
The rule is that the type of “recipient” expression that accesses a protected instance must be at least the same as the type declaration containing member access. For a precise statement of the rule and some illustrative examples, see Section 3.5.3 of the C # 4.0 Specification.
By the way, C ++ also has this rule.
This rule is often misunderstood. For a more detailed analysis of this rule and some other consequences of secure access, see my articles on this subject. The most relevant articles I wrote on this subject are this one and this one . There are a bunch of more articles I wrote on related topics here (although some of them will go over the topic of secure access itself and on how to use secure access to create a data model with parent links.)
source share