in my C#-project, I have a class which contains a List
public class MyClass
{
public MyClass parent;
public List children;
...
}
If you hand the caller the List
, you can't control this; you can't even subclass List
, since the add/remove are not virtual
.
Instead, then, I would expose the data as IEnumerable
:
private readonly List children = new List();
public void AddChild(MyClass child) {...}
public void RemoveChild(MyClass child) {...}
public IEnumerable Children {
get {
foreach(var child in children) yield return child;
}
}
(the yield return
prevents them just casting it)
The caller can still use foreach
on .Children
, and thanks to LINQ they can do all the other fun things too (Where
, First
, etc).