A WPF program I’m writing in C# has the following interface on the back-end:
public interface CatalogMenu<T> : CatalogItem where T : CatalogItem
{
void AddCatalogItem(T toAdd);
void RemoveCatalogItem(T toRemove);
List<T> AvailableCatalogItems { get; }
}
I have three classes that implement the interface, each with a different T. The problem is that I want to create a List<CatalogMenu<CatalogItem>> to bind to a ListView, but this property in the View-Model doesn’t compile… (thing1, thing2, and thing3 all implement the interface with a different T)
public List<CatalogMenu<CatalogItem>> MenuCategories
{
get
{
return new List<CatalogMenu<CatalogItem>>(){
ModuleCatalog.thing1,
ModuleCatalog.thing2,
ModuleCatalog.thing3
};
}
}
As much as I’d like it to, the compiler won’t let me treat the “classes implementing CatalogMenu<T> where T is a CatalogEntity” as a “CatalogMenu<CatalogItem>“. I want to present each class implementing the interface to the user through a common interface.
If I left out any details, be a little patient with me; my head’s spaghetti after reading about covariance for the last 30 minutes in an attempt to figure out a way to fix this.
.Net does not support covariant classes.
If you add an
ICatalogMenu<out T>, you will be able to cast any CatalogMenu toICatalogMenu<CatalogItem>and put it into aList<ICatalogMenu<CatalogItem>>You can accomplish the same effect using an ordinary non-generic interface or base class.