Is a bad form a reference to a derived type in a base type?

I have a tree structure of categories / files. Both categories and files can have parents, so I got them from a common base class with a parent property. Since all parents will obviously always be categories (files cannot be parents), it seems to make sense to make the parent property node type CategoryNode.

Is this a bad form for a base class to reference a derived class? If so, why? What is the best way to structure this, if so?

class Node { public CategoryNode Parent {get; set;} } class File : Node { ... } class CategoryNode : Node { ... } 
+8
inheritance c # oop
source share
4 answers

If the Parent property is actually a common property of all descendants and always a good CategoryNode, this is not a problem. Semantically this is correct and technically, I think it is correct as soon as you stay in the same library (to avoid circular links).

This can be a problem when writing code as follows:

 // BAD CODE if(myProp is subclassA) { ... } else if (myProp is syubclassB) { ... } 

This code is bad because you are losing the advantage of inheritance.

Even the .NET Framework has such constructs . The first example that comes to my mind is the XObject.Parent property.

XElement inherits XObject, and XObject publishes a property of type XElement. Same as your fragment.

+4
source share

You can do...

 interface IParent { ... } class Node { public IParent Parent {get; set;} } class File : Node { ... } class CategoryNode : Node, IParent { ... } 

Thus, you do not need to refer to a derived object in the base class, plus, you are more flexible in that you can become a parent if you get additional types of objects at a later point in time. In addition, any functionality that matters only for parent can be declared in this interface.

+7
source share

The base class does not need to know who retrieves it.

If this is your case, you probably don't want inheritance. You should just use some form of grip.

The file and CategoryNode must contain a Node member in your case.

+1
source share

Other options will be to change the class hierarchy to make CategoryNode the root class (a) or change the type of the property to Node (b).

Both of these features are not very good: (a) The file will have all the CategoryNode functionality that it does not need. (b) It will hide the type of object (which is always CategoryNode). This can lead to errors with errors elsewhere in your code. For example, if you forget, there is always an instance of CategoryNode.

Given this, I believe the current code is fine.

+1
source share

All Articles