Reputation: 6547
I have an error in the following implementation. It says that OnlineWebStore_Process cannot implement the interface IWebStore because they don't have a matching return type. But the method returns Item which implements the IItem interface used as return type in the IWebStore interface. What's a good solution to this problem?
public interface IItem
{
string id { get; set; }
string name { get; set; }
}
public interface IWebStore
{
List<IItem> GetOnlineItems();
}
public class Item : IItem
{
public Item(string _id)
{
id = _id;
}
public string id { get; set; }
public string name { get; set; }
}
public class OnlineWebStore_Process : IWebStore
{
public List<Item> GetOnlineItems()
{
List<Item> items = new List<Item>();
return items
}
}
Upvotes: 0
Views: 88
Reputation: 44439
public class OnlineWebStore_Process : IWebStore
{
public List<IItem> GetOnlineItems()
{
List<IItem> items = new List<IItem>();
return items;
}
}
Your method signature has to be exactly the same, you can't take a subclass instead. If you do return a subclass you're losing a part of your abstraction and the interface contract is broken.
Upvotes: 5
Reputation: 3626
Firstly you method signatures need to be same. And secondly List<Item>
is not child of List<IItems>
like Item
and IItem
. They are totally different type.
Upvotes: 0
Reputation: 859
public List<Item> GetOnlineItems()
{
List<Item> items = new List<Item>();
return items
}
Here you return List instead of List. This way you don't have your IWebStore method implemented. Here is the correct way:
public List<IItem> GetOnlineItems()
{
List<IItem> items = new List<IItem>();
items.Add( new Item( "1" ) ); // Adding an instance, which implements the interface IItem
return items;
}
Upvotes: 1