Search code examples
c#listpropertiescode-access-security

How to restrict to add an item to List<T>?


I have Class called Person containing to properties, Father and List of Children.

I want every one to use only AddChild Method to add children, not the List.Add method , so how do I restrict use of it?

public class Person
{
  private List<Person> _children = new List<Person>();
  public string Name { get; set; }
  public Person Father { get; set; }
  public List<Person> Children 
  { 
    get
    {
       return _children;
    } 
  }
  public void AddChild(string name)
  {
      _children.Add( new Person { Name = name, Father = this });
  }
}

Solution

  • Change your Children property to this:

    public IList<Person> Children 
    { 
      get
      {
         return _children.AsReadOnly();
      } 
    }