C#: Why I cannot call protected method from derived class

Someone posted a comment in the internal alias on protected member access. The question is that the following code does not compile with the error “cannot access protected member Class1.Foo()“

public

classClass1

{

protectedvoid Foo()

{

}

}

publicclassClass2 : Class1

{

privatevoid Test()

{

Class2 a = newClass2();

Class1 b = newClass2();

a.Foo();

b.Foo(); // Fails to compile

}

}

The argument that this code should work is that since Class1 is the base class of Class2 the access should be allowed. Long back (in another life) I had seen the same issue in C++. This is what I replied to the question….

The same issue exists in C++ as well, I think similar rationale will exist for C#. The following C++ code won’t compile as well

class

Class1

{

protected

:

void Foo ()

{

}

};

class

Class2 : public Class1

{

public

:

void Test ()

{

Class2* a =

new Class2 ();

Class1* b =

new Class2 ();

a->Foo();

b->Foo();

}

};

This is because b is pointer (or reference) to a base class. For all we know b could point to an object of any class derived from Class1. If this call was allowed then it would break encapsulation as you would get access to a method inside the derived class

Frans, since Foo is in Class1 it might change some state in Class1 when called. This state might be important to a class Class3 which has inherited from Class1. Since Foo is protected Class3 will never take into account a state change caused by Foo by any call from external entity and so if this call is allowed it might throw Class3 out of gear.