in my C#-project, I have a class which contains a List
public class MyClass
{
public MyClass parent;
public List children;
...
}
Make the list private, and create public methods to access its content from outside the class.
public class MyClass
{
public MyClass Parent { get; private set; }
private List _children = new List();
public IEnumerable Children
{
get
{
// Using an iterator so that client code can't access the underlying list
foreach(var child in _children)
{
yield return child;
}
}
}
public void AddChild(MyClass child)
{
child.Parent = this;
_children.Add(child);
}
public void RemoveChild(MyClass child)
{
_children.Remove(child);
child.Parent = null;
}
}
By the way, avoid declaring public fields, because you can't control what client code does with them.