Maybe this is already answered somewhere else, but this is the kind of situation where the question in itself is hard to formulate. Excuse me in advance if it is the case.
I have a container class who contains base properties and a list of items of the generic type specified in the class definition.
public class Container<TItem> where T : IItem
{
public string PropA {get; set;}
public List<TItem> Items {get; set;}
}
IITem is only an empty interface used for the purpose of grouping specific classes. It will be clearer in a short while.
public interface IITem
{}
I then have some classes who inherits this interface.
public class ItemA : IItem
{
public string ItemAProperty { get; set; }
}
public class ItemB : IItem
{
public int ItemBProperty { get; set; }
}
Here is the problem. I have a method who populate a Container class and I want it to return it. So, I have this :
public Container<IItem> GetItems(int itemCategory)
{
Container<IItem> items;
switch(itemCategory)
{
case 1 :
items = GetItemsA(); // Will return an instance of Container<ItemA>.
break;
case 2:
items = GetItemsB(); // Will return an instance of Conainter<ItemB>.
break;
}
}
The lines begining with item = GetItems... don't compile, indicating :
Container<ItemA> can't be cast as Container<IITem>.