Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Forbid public Add and Delete for a List<T>

Tags:

c#

list

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

like image 420
Aaginor Avatar asked Jun 16 '10 12:06

Aaginor


1 Answers

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).

like image 50
Marc Gravell Avatar answered Oct 05 '22 22:10

Marc Gravell