Is it bad form to refer to a derived type in a base type?

c#, inheritance, oop

Solution

If the property `Parent` is actually a common properties of all descendants and always of kind CategoryNode, it's not a problem. Semantically speaking it's correct and technically I think its correct too as soon as you remain in the same library (to avoid circular references).

This can be a problem when you write code like this :

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

This code is bad, because you loose the advantage of inheritance.

Even in the .Net Framework there is such constructs. The first example that comes in my mind is the XObject.Parent property.

XElement inherits XObject, and XObject publish a property of type XElement. Same as your snippet.

Problem

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 { ... } ```

Original source