C# protected members accessed via base class variable

Roman picture Roman · Dec 2, 2009 · Viewed 10.7k times · Source

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!

Answer

Eric Lippert picture Eric Lippert · Dec 3, 2009

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