Alex Rivera | Logout

Forbid public Add and Delete for a List<T>

Asked 2010-06-16T12:01:30.893
18

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

Edit
Report

1 Answer

0

You can encapsulate the list in the class by making it private, and offer it as a ReadOnlyCollection:

public class MyClass {

  public MyClass Parent { get; private set; };

  private List<MyClass> _children;

  public ReadOnlyCollection<MyClass> Children {
    get { return _children.AsReadOnly(); }
  }

  public void AddChild(MyClass item) {
    item.Parent = this;
    _children.Add(item);
  }

  public void DeleteChild(MyClass item) {
    item.Parent = null;
    _children.Remove(item);
  }

}

You can make the Parent a property with a private setter, that way it can't be modified from the outside, but the AddChild and DeleteChild methods can change it.

answered 2010-06-16T12:07:48.127

Your Answer