Reputation: 2588
I got a tree structure in C#.
Each node in the tree contains a reference to a parent and a collection of children. The process of creating a child node is likewise -
This has worked great for me just up until now. I encountered a situation where some objects needed a reference to their parent already in their constructor, even though they did not have it yet, and will receive it only after they exit the constructor and be added to their parent's collection. (As in stage 3)
I thought of a possible solutions which I'm not sure of -
Each parent node should propagate itself to its child upon creation. The problem with this case is a bit more clumsy constructors but also the Parent property would be set twice. Once in step 2, and one more time in step 3.
I figured that this must be a common problem, therefore someone must have found out a better solution.
Just for general knowledge - this tree structure is ViewModel based for WPF's TreeView.
Comments will be much appreciated.
Thanks!
Upvotes: 1
Views: 715
Reputation: 96840
The first question I'd ask is: why doesn't your parent class implement a method that looks like this?
public void AddChild(object parameters)
{
Children.Add(new ChildNode(this, parameters));
}
Is there any other circumstance in your application in which a ChildNode
object can be created? If so, what is it, and why does it exist?
Upvotes: 2
Reputation: 1480
I think you have one of two options:
I'd prefer the second solution, because it will allow you to rerun the logic if your node happens to get re-parented. It also allows for your nodes to be trimmed from the tree (Parent = null).
Upvotes: 1