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 class Class1{ protected void Foo() { }}public class Class2 : Class1{ private void Test() { Class2 a = new Class2(); Class1 b = new Class2(); 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
Comments
- Anonymous
November 09, 2005
The comment has been removed - Anonymous
November 09, 2005
The comment has been removed - Anonymous
May 30, 2007
At least in C++ this protection can be disabled with an appropriate change to Class2's source file. Yes, I have done so. - Anonymous
June 06, 2012
The comment has been removed