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;
}
}
}
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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With