Question

I have something like this:

class Node
{
    protected Node Parent
    {
        get; private set;
    }
}

class NodeDerived : Node
{
    void SomeMethod()
    {
        Node parentIterator = this.Parent;

        while (parentIterator != null)
        {
            // ... some logic

            parentIterator = parentIterator.Parent; // Here's the error
        }
    }
}

But for some strange reason, I can't access parentIterator.Parent property:

error CS1540: Cannot access protected member `Node.Parent' via a qualifier of type `Node'. The qualifier must be of type `NodeChild' or derived from it

Why is this happening? By the way, I also discovered that while I can access this.Parent, I can't access ((Node) this).Parent.

Was it helpful?

Solution

From the C# 5 spec, section 3.5.3:

When a protected instance member is accessed outside the program text of the class in which it is declared, and when a protected internal instance member is accessed outside the program text of the program in which it is declared, the access must take place within a class declaration that derives from the class in which it is declared. Furthermore, the access is required to take place through an instance of that derived class type or a class type constructed from it. This restriction prevents one derived class from accessing protected members of other derived classes, even when the members are inherited from the same base class.

So you're fine to access the Parent property of any NodeDerived object:

NodeDerived derivedNode = ...;
Node parent = derivedNode.Parent;

... but you can't access the Parent property for a node type which isn't NodeDerived or a subclass.

Using this.Parent works because the compile-time type of this is NodeDerived.

I suspect you'll want to make your Parent property public - assuming that you want this code to work with nodes other than NodeDerived.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top