in my C#-project, I have a class which contains a List
public class MyClass
{
public MyClass parent;
public List children;
...
}
You can encapsulate the list in the class by making it private, and offer it as a ReadOnlyCollection:
public class MyClass {
public MyClass Parent { get; private set; };
private List _children;
public ReadOnlyCollection Children {
get { return _children.AsReadOnly(); }
}
public void AddChild(MyClass item) {
item.Parent = this;
_children.Add(item);
}
public void DeleteChild(MyClass item) {
item.Parent = null;
_children.Remove(item);
}
}
You can make the Parent
a property with a private setter, that way it can't be modified from the outside, but the AddChild
and DeleteChild
methods can change it.