Probably a simple question.
I have an interface (MyInterface) that defines a property like so:
IList<IMenuItem> MenuCollection { get; }
And the class implementing MyInterface
public class MyClass : MyInterface
{
public ObservableCollection<MenuItemBase> MenuCollection
{
get
{
...
}
}
....
}
From what I read, ObservableCollection inherits from a Collection which is a IList, and I have MenuItemBase class that imlements IMenuItem – wouldn’t that satisfy the interface?
I suppose interfaces must be implemented explicitly?
I also tried this:
public class MyClass : MyInterface
{
public IList<IMenuItem> MenuCollection MenuCollection
{
get
{
if(_menuCollection == null)
_menuCollection = new ObservableCollection<MenuItemBase>();
return _menuCollection as IList<IMenuItem>;
}
}
private ObservableCollection<MenuItemBase> _menuCollection;
}
Seems like a workaround hack (and I did run into a few issues saying that MenuCollection was not instantiated) to get the interface to be satisfied…. is there a better way to implement IInterface1<IInterface2> objects?
The reason why I need this kind of abstraction is because I’m building a prism / unity app and want to decouple the menu viewmodel as much as possible from the ribbon ui that displays the menu.
This has nothing to do with generic variance
There are multiple answers talking about generic variance. This has nothing to do with the example. If you try to implement a property defined as
IListwith anArrayList(no generics), you will see that it’s still not possible to do so.The correct answer
This behavior is because if you could implement
MenuCollectionas a property of some type implementingIList<T>(or deriving from it, if it were not specified as an interface), then this would be possible:In this last line, you have assigned a
List<MenuItemBase>(which is OK as far asMyInterfacecan tell, sinceMyInterface.MenuCollectionis of typeIList<MenuItemBase>) to a property that is of typeObservableCollection<MenuItemBase>.Of course this is not legal to do, as
List<MenuItemBase>clearly is not derived fromObservableCollection<MenuItemBase>. But it would be a possibility if you could implement the interface like that.