0

I have made a base class Node with methods for adding and removing children, handling parents and searching for ancestors, descendants etc. So far so good.

Now I want to make a derived type TreeNode : Node that benifits from all these Node-features but at the same time restricting children and parent to have the same TreeNode type. As it is now I still have Node as type for children and parent.

Can I somehow make the property and method argument types of the Node class change to match the type of the derived class without having to manually override or "new"?

class Node
{
  public TypeOfThisInstance Parent { get; }
}

class TreeNode : Node
{
}

TreeNode.Parent should now be a TreeNode and not a Node.

1
  • Why do you even want to do that? How is TreeNode different from Node? Commented Apr 22, 2012 at 14:00

2 Answers 2

1

Using Generics:

public class BaseNode<T> where T : BaseNode<T>
{
  private T _parent;
  public T Parent { get { return _parent;} }
}
public class Node : BaseNode<Node>
{
} 
public class TreeNode : BaseNode<TreeNode>
{
}
Sign up to request clarification or add additional context in comments.

3 Comments

I think, the limitations of this approach should be pointed out: you can make class Node : BaseNode<int> or class TreeNode : BaseNode<Node>. It doesn't make much sense, but you can do it. You can avoid some (but not all) of those problems by using generic constraints.
Yep, @svick is correct. You can add a constraint on the BaseNode class like: where T : BaseNode<T>
Thanks. I'm pretty sure I have tried this before and only got StackOverflowExceptions ... strange... It seem to work fine now!
0

I think you need to build the composite design pattern. It is all about creating tree-like structures where the leaves in the structure can be treated in the same way as the branches(which are substructures that can contain multiple leaves, as well as other branches). The idea here is that, to make life easier, you should be able to treat the leaves and compositions of leaves in a tree structure the same.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.