Steven Batham
Steven Batham

Reputation: 39

Can a collection element reference the collection?

I have a class that arranges in a tree structure by optionally including lists of itself, something like:

class MyClass
{
    List<MyClass> MyClassList;
    ...
}

Is there any way an element can call its parent collection? Like,

class MyClass
{
    List<MyClass> MyClassList;
    ...

    private void AddItemToParentCollection()
    {
        parent.MyClassList.Add(new MyClass());
    }
}

I think I could write a function that tells a class where it is in the tree (and so where it's parent is) by traversing the tree until it finds itself, but I'm hoping there's a neater way.

Upvotes: 1

Views: 110

Answers (1)

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236218

class Node
{
    Node parent;
    List<Node> children = new List<Node>();

    public void Add(Node child)
    {
        if (child.Parent != null)
            // throw exception or call child.Parent.Remove(child)

        children.Add(child);
        child.Parent = this;
    }

    public void Remove(Node child)
    {
        if (child.Parent != this)
           // throw exception

        children.Remove(child);
        child.Parent = null;
    }
}

With such structure you can add items to parent collection (not sure it should be responsibility of child node):

private void AddItemToParentCollection()
{
    if (Parent == null)
       // throw exception 

    Parent.Add(new Node());
}

Upvotes: 1

Related Questions