title: C#: Add child to collection and set child's parent in same call
body: <p>I'm building a sort of domain layer and I would like to be able to implement the following methods:</p>
  
  <p>[Note: ISet is a collection class which doesn't permit duplicates, according to checking using .Equals().]</p>
  
  <pre><code>public class Parent
  {
  public ISet Children = new HashedSet&lt;Child&gt;;
  public void AddChild()
  {
  ...
  }
  public void RemoveChild()
  {
  ...
  }
  }
  
  public class Child
  {
  public Parent Parent
  {
  get {...} set {...}
  }
  }
  </code></pre>
  
  <p>Such that the following tests would pass:</p>
  
  <p><strong>When parent.AddChild(child) is called:</strong></p>
  
  <ul>
  <li>parent.Children contains child. </li>
  <li>child.Parent is set to parent. </li>
  <li>if child had a previous Parent, then that Parent's Children collection no longer contains child</li>
  </ul>
  
  <p><strong>When calling parent.RemoveChild(child):</strong></p>
  
  <ul>
  <li>child.Parent == null.</li>
  <li>parent.Children doesn't contain child.</li>
  </ul>
  
  <p>And that setting child.Parent is equivalent to calling parent.AddChild().
  And that setting child.Parent = null when the child has an existing parent is equivalent to calling parent.RemoveChild().</p>
  
  <p>But I really can't seem to do it!</p>
  
  <p>This must be very common logic in domain layers using e.g. NHibernate, so I was wondering how other people do it?</p>