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.
Jon is correct; this has nothing to do with generic variance. However, he does not mention that the feature you are wanting is called return type covariance.
That is, if Animal is the base type of Giraffe, then an interface method that returns an Animal, or a virtual method that returns an Animal, may be implemented/specialized by a method that returns a Giraffe. Since every Giraffe is an Animal, the contract is fulfilled.
C# does not support return type covariance; for that matter, neither does the CLR. Some languages support return type covariance; C++ for example comes to mind. (The C++/CLI implementation does some sneaky tricks to work around the limitations of the CLR.) The return type of an implemented interface method, the type of a property, and so on, all must match exactly in C#.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With