Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automatically set parent reference on child items

Tags:

c#

I have a class that contains an IList<T> property called Children. Each child should reference its parent. My solution has been to set the ChildClass.Parent property in the ParentClass.Children getter. Is there a better way, or is this the best solution?

class ParentClass
{
    private IList<ChildClass> _children;

    public virtual IList<ChildClass> Children
    {
        get
        {
            // make sure each child refers to its parent (this)
            foreach (ChildClass c in _children)
            {
                c.Parent = c.Parent ?? this;
            }
            return _children;
        }
        set
        {
            _children = value;
        }
    }
}
like image 908
nw. Avatar asked Feb 02 '26 14:02

nw.


1 Answers

It could just be me...but this looks like a bad design.

If it's a true Parent -> Child relationship, you shouldn't allow anybody to create an Orphan Child. Therefore, the Parent should be set on the Child at the time of creation.

I would probably do something like:

class ChildClass
{
    private ParentClass _parent;

    public ChildClass(ParentClass parent)
    {
        _parent = parent;
    }
}

And then:

class ParentClass
{
    private List<ChildClass> _children;

    public virtual ReadOnlyCollection<ChildClass> Children
    {
        get
        {
            return _children.AsReadOnly();
        }
    }

    public virtual ChildClass CreateChild()
    {
        // Set parent in child class constructor
        ChildClass newChild = new ChildClass(this);

        _children.Add(newChild);

        return newChild;
    }
}
like image 102
Justin Niessner Avatar answered Feb 04 '26 06:02

Justin Niessner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!