Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't my use of "protected" work? [duplicate]

Tags:

c#

protected

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
    }
}
like image 265
Miria Avatar asked Nov 28 '22 00:11

Miria


1 Answers

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.)

like image 117
Eric Lippert Avatar answered Dec 18 '22 07:12

Eric Lippert