Search code examples
c#parent-childfriendtree-structure

Tree structure with parents and children


I'm trying to make a tree structure of parents and children. The problem is that I only want to be able to assign the parent of a child in the child and parent classes, and nowhere else:

public class Parent
{
    public static Parent Root = new Parent();
    
    private List<Child> children = new List<Child>();
    public ReadOnlyCollection<Child> Children
    {
        get { return children.AsReadOnly(); }
    }

    public void AppendChild(Child child)
    {
        child.Parent.RemoveChild(child);
        child.children.Add(child);
        child.Parent = this; //I need to asign the childs parent in some way
    }
    public void RemoveChild(Child child)
    {
        if (this.children.Remove(child))
        {
            child.Parent = Parent.Root; //here also
        }
    }
}
public class Child : Parent
{
    private Parent parent = Parent.Root;
    public Parent Parent
    {
        get { return this.parent; }
        private set { this.parent = value; } //nothing may change the parent except for the Child and Parent classes
    }
}

By a not-C# programmer, I was told to use friends (like in C++), but those aren't implemented in C#, and all my other solutions failed.


Solution

  • This may not answer your question but it is an alternative. This is a node structure and you could use something like this:

    public class Node
    {
        private Node _parent;
        private List<Node> _children = new List<Node>();
    
        public Node(Node parent)
        {
            _parent = parent
        }
    
        public ReadOnlyCollection<Node> Children
        {
            get { return _children.AsReadOnly(); }
        }
    
        public void AppendChild(Node child)
        {
            // your code
        }
    
        public void RemoveChild(Node child)
        {
            // your code
        }
    }
    

    I see @zmbq has just edited to suggest something similar.