in my C#-project, I have a class which contains a List
public class MyClass
{
public MyClass parent;
public List<MyClass> children;
...
}
I want to prevent the user of the class from Adding (and Deleting) an Element to the children-List, but he shall still be able to parse its elements. I want to handle the Adding and Deleting within MyClass, providing an AddChild(MyClass item) and DeleteChild(MyClass item) to ensure that, when an item is added to the child list, the parent of that item will be set properly.
Any idea how to do this besides implementing my own IList?
Thanks in advance, Frank
If you hand the caller the List<T>
, you can't control this; you can't even subclass List<T>
, since the add/remove are not virtual
.
Instead, then, I would expose the data as IEnumerable<MyClass>
:
private readonly List<MyClass> children = new List<MyClass>();
public void AddChild(MyClass child) {...}
public void RemoveChild(MyClass child) {...}
public IEnumerable<MyClass> 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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With