Hi!
While implementing a design using nested generic collections, I stumbled across those limitations apparently caused by C#'s invariant Generics:
Cannot convert from 'Collection<subtype of T> to 'Collection<T>'
That means, the following will not work, apparently due to the invariance of Generics:
class Outer<TInner, TInnerItem> where TInner : Inner<TInnerItem>
{
public void Add(TInner item)
{
item.Outer = this; // ERROR:
// Cannot implicitly convert from Outer<TInner, TInnerItem>
// to Outer<Inner<TInnerItem>, TInnerItem>
}
}
class Inner<TInnerItem> : ICollection<TInnerItem>
{
Outer<Inner<TInnerItem>, TInnerItem> _outer;
public Outer<Inner<TInnerItem>, TInnerItem> Outer
{
set { _outer = value; }
}
}
(In the actual code, both Inner<>
and Outer<>
implement ICollection<>
.)
I need the Inner<>
objects to have a reference to its container collection in order to access some of its data.
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 Inner<>
class?
Cheers!