Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# protected members accessed via base class variable [duplicate]

It may seems rather newbie question, but can you explain why method Der.B() cannot access protected Foo via Base class variable? This looks weird to me:

public class Base
{
    protected int Foo;
}

public class Der : Base
{
    private void B(Base b) { Foo = b.Foo; } // Error: Cannot access protected member

    private void D(Der d) { Foo = d.Foo; } // OK
}

Thanks!

like image 659
Roman Avatar asked Dec 02 '09 22:12

Roman


3 Answers

This is a frequently asked question. To figure out why this is illegal, think about what could go wrong.

Suppose you had another derived class Frob derived from Base. Now you pass an instance of Frob to Der.B. Should you be able to access Frob.Foo from Der.B? No, absolutely not. Frob.Foo is protected; it should only be accessible from Frob and subclasses of Frob. Der is not Frob and is not a subclass of Frob, so it does not get access to Frob's protected members.

If that's not clear, see my article on the subject:

http://blogs.msdn.com/ericlippert/archive/2005/11/09/491031.aspx

like image 160
Eric Lippert Avatar answered Sep 23 '22 17:09

Eric Lippert


In B you are trying to access a protected member of another class. The fact that you are inheriting from that class is irrelevant. In D you are accessing a protected member of the base class of your current class. In this context you can access anything from Der and the protected members of the type it is inheriting from.

like image 31
Yuriy Faktorovich Avatar answered Sep 23 '22 17:09

Yuriy Faktorovich


You can work around this limitation by declaring a static method in the base class:

public class Base
{
    protected int Foo;

    protected static int GetFoo(Base b)
    {
        return b.Foo;
    }
}

public class Der : Base
{
    private void B(Base b) { Foo = GetFoo(b); } // OK
}
like image 39
Jesse McGrew Avatar answered Sep 20 '22 17:09

Jesse McGrew