I'm running into an issue where I have one generic that I'm trying to cast to another where the second's generic T parameter is a subclass of the one used in the first.
Here's my code, simplified for understanding...
public partial class HierarchicalItem
{
public ObservableHierarchicalCollection<HierarchicalItem> ContainingCollection{ get; private set; }
public HierarchicalItem Parent{ get{
return (ContainingCollection != null)
? ContainingCollection.Owner
: null;
}}
}
public partial class HierarchicalItem
{
public class ObservableHierarchicalCollection<T> : ObservableCollection<T>
where T : HierarchicalItem
{
public ObservableHierarchicalCollection(HierarchicalItem owner)
{
this.Owner = owner;
}
public HierarchicalItem Owner{ get; private set; }
private void ExistingMemberCheck(T item)
{
if(item.ContainingCollection != null) throw new ExistingMemberException();
item.ContainingCollection = this; // <-- This fails because of casting
}
protected override void InsertItem(int index, T item)
{
ExistingMemberCheck(item);
base.InsertItem(index, item);
}
protected override void SetItem(int index, T item)
{
CheckParent(item);
// Get the item and unhook the hierarchy
var existingItem = this[index];
existingItem.ContainingCollection = null;
base.SetItem(index, item);
}
protected override void RemoveItem(int index)
{
// Get the item and unhook the hierarchy
var existingItem = this[index];
existingItem.ContainingCollection = null;
base.RemoveItem(index);
}
}
}
So how do I get around this?