title: Nested generic collections: How to implement reference from item to container?
body: <p>While implementing a design using nested generic collections, I stumbled across those  limitations apparently caused by C#'s invariant Generics:</p>
  
  <pre>Cannot convert from 'Collection&lt;subtype of T&gt; to 'Collection&lt;T&gt;'</pre>
  
  <p>That means, the following will not work, apparently due to the invariance of Generics:</p>
  
  <pre><code>class Outer&lt;TInner, TInnerItem&gt; where TInner : Inner&lt;TInnerItem&gt;
  {
      public void Add(TInner item)
      {
          item.Outer = this; // ERROR:
              // Cannot implicitly convert from Outer&lt;TInner, TInnerItem&gt; 
              // to Outer&lt;Inner&lt;TInnerItem&gt;, TInnerItem&gt;
      }
  }
  
  class Inner&lt;TInnerItem&gt; : ICollection&lt;TInnerItem&gt;
  {
      Outer&lt;Inner&lt;TInnerItem&gt;, TInnerItem&gt; _outer;
  
      public Outer&lt;Inner&lt;TInnerItem&gt;, TInnerItem&gt; Outer
      {
          set { _outer = value; }
      }
  }
  </code></pre>
  
  <p>(In the actual code, both <code>Inner&lt;&gt;</code> and <code>Outer&lt;&gt;</code> implement <code>ICollection&lt;&gt;</code>.)</p>
  
  <p>I need the <code>Inner&lt;&gt;</code> objects to have a reference to its container collection in order to access some of its data. </p>
  
  <p>How would you implement these nested collections, preferably using a generic approach as outlined above? How would you set the reference to the container collection in the <code>Inner&lt;&gt;</code> class? </p>
  
  <p>Cheers!</p>