in my C#-project, I have a class which contains a List
public class MyClass
{
public MyClass parent;
public List children;
...
}
Beside of implementing your own IList<T>
you could return a ReadOnlyCollection<MyClass>.
public MyClass
{
public MyClass Parent;
private List<MyClass> children;
public ReadOnlyCollection<MyClass> Children
{
get { return children.AsReadOnly(); }
}
}
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<MyClass> _children;
public ReadOnlyCollection<MyClass> 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.