Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 });
  }
}
like image 882
Prashant Cholachagudda Avatar asked Oct 07 '09 11:10

Prashant Cholachagudda


3 Answers

Expose Children as ReadOnlyCollection:

public IList<Person> Children  
{  
    get 
    { 
       return new ReadOnlyCollection<Person>(_children);
    }  
} 
like image 179
Pawel Lesnikowski Avatar answered Nov 11 '22 14:11

Pawel Lesnikowski


Change your Children property to this:

public IList<Person> Children 
{ 
  get
  {
     return _children.AsReadOnly();
  } 
}
like image 38
Thomas Weller Avatar answered Nov 11 '22 13:11

Thomas Weller


Expose Children as IEnumerable<T>

like image 23
Alex Reitbort Avatar answered Nov 11 '22 13:11

Alex Reitbort