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 subclassList<T>, since the add/remove are notvirtual.Instead, then, I would expose the data as
IEnumerable<MyClass>:(the
yield returnprevents them just casting it)The caller can still use
foreachon.Children, and thanks to LINQ they can do all the other fun things too (Where,First, etc).