Here's a thinned out version of the classes I have.
public abstract class BaseParent { }
public abstract class ChildCollectionItem<T>
where T : BaseParent
{
// References a third-party object that acts as the parent to both the collection
// items and the collection itself.
public T parent;
// References the collection to which this item belongs. The owning collection
// will share the same parent type. The second type argument indicates what
// type of items the collection will store.
public ChildCollection<T, ChildCollectionItem<T>> owningCollection;
}
public abstract class ChildCollection<T, U> : CollectionBase
where T : BaseParent
where U : ChildCollectionItem<T>
{
// References a third-party object that acts as the parent to both the collection
// items and the collection itself.
public T parent;
// Adds an item of type 'U' to the collection. When added, I want to set the
// owningCollection value of the item to 'this' collection.
public int Add(U item)
{
int indexAdded = this.List.Add(item);
// THIS LINE IS THROWING A COMPILE ERROR - Cannot convert type
// 'ChildCollection<T, U>' to 'ChildCollection<T, ChildCollectionItem<T>>'
item.owningCollection = this;
return indexAdded;
}
I realize this problem is probably due to the fact that the ChildCollection class isn't aware of the type constraints set in ChildCollectionItem, because if it was there shouldn't be a problem here. Type 'U' should always be a ChildCollectionItem where the ChildCollectionItem 'T' is always the same as the ChildCollection 'T'.
What I need to know is if there is a way I can cast 'this' so that it compiles, or modify my classes / constraints so the compiler can handle this without a cast.