title: Enforcing parent-child relationship in C# and .Net
body: <p>Let's take the following two classes:</p>
  
  <pre><code>public class CollectionOfChildren
  {
      public Child this[int index] { get; }
      public void Add(Child c);
  }
  
  public class Child
  {
      public CollectionOfChildren Parent { get; }
  }
  </code></pre>
  
  <p>Child's Parent property should always return the CollectionOfChildren that the Child is in, or null if the child is not in such a collection. Between these two classes, this invariant should be maintained, and should not be breakable (well, easily) by the consumer of the class.</p>
  
  <p>How do you implement such a relationship? CollectionOfChildren cannot set any of the private members of Child, so how is it supposed to inform Child that it was added to the collection?
  (Throwing an exception is acceptable if the child is already part of a collection.)</p>
  
  <hr>
  
  <p>The <code>internal</code> keyword has been mentioned. I am writing a WinForms app at the moment, so everything is in the same assembly, and this is essentially no different than <code>public</code>.</p>