I have a category/file tree structure. Both categories and files can have parents, so I derived them from a common base class that has a Parent property. Since all parents will obviously always be categories (files can't be a parent), it seems to make sense to make the Parent property of the node be the CategoryNode type.
Is it bad form for the base class to refer to the derived class? If so, why? What's a better way to structure this, if so?
class Node {
public CategoryNode Parent {get; set;}
}
class File : Node {
...
}
class CategoryNode : Node {
...
}
No. A reference to a derived class must actually refer to an instance of the derived class (or null).
similarly a derived object is a base class object (as it's a sub class), so it can be pointed to by a base class pointer. However, a base class object is not a derived class object so it can't be assigned to a derived class pointer.
// As base-class pointer cannot access the derived class variable.
Derived class pointer cannot point to base class.
You could do ...
interface IParent {
...
}
class Node {
public IParent Parent {get; set;}
}
class File : Node {
...
}
class CategoryNode : Node, IParent {
...
}
This way, you don't need to refer to a derived object in the base class, plus, you're more flexible in what can actually become a parent, in case you get additional object types at a later point in time. Also, any functionality that is relevant just for a parent can be declared in that interface.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With