Reputation: 8721
class MyClass { MyClass parent; }
class Container : MyClass { List<MyClass> children; }
class NonContainer : MyClass {}
I'd like to be able to make List<MyClass> children
automatically set parent
value to current Container
for each MyClass
instance that is being added to it automatically. I really wouldn't like to place a separate method that does this everywhere I add MyClass
to children
in my code.
Throughout my application, I add items to the list in three ways:
children.Add()
children.AddRange()
new List<MyClass>(){ new MyClass(){}, /* ... */, new MyClass(){} }
Maybe there is some better way to make all first gen children know who their parent object is?
Upvotes: 0
Views: 66
Reputation: 112622
Keep the children list private and make the children accessible through public methods and properties
class Container : MyClass {
private readonly List<MyClass> _children = new List<MyClass>();
public void AddChild(MyClass child)
{
child.Parent = this;
_children.Add(child);
}
public void AddChildren(IEnumerable<MyClass> children)
{
foreach (MyClass child in children) {
AddChild(child);
}
}
public IEnumerable<MyClass> Children { get { return _children; } }
}
Upvotes: 3
Reputation: 9790
Inherit the List
like this:
public class ChildrenList : List<MyClass>
{
public MyClass Parent { get; private set; }
public ChildrenList(MyClass parent) { this.Parent = parent; }
public override void Add(MyClass item)
{
item.Parent = Parent;
base.Add(item);
}
}
Then use it inside your container:
class Container : MyClass { List<MyClass> children = new ChildrenList(parent); }
Upvotes: 0