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 (4)

  1. Frans Bouma says:

    though… b is of type class1, and Foo is in class1, so no matter what type b really is (derived type), Foo is in class1, so I don’t see the point of not allowing it because of the various subtypes.

    However, I find it pretty obscure to call a protected method on the outside of an object, just because you’re happen to be in a type in the same inheritance chain.

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

  3. Joshua says:

    At least in C++ this protection can be disabled with an appropriate change to Class2’s source file. Yes, I have done so.

  4. can v execute C# console application without main function?