David Conlisk David Conlisk - 3 months ago 10
C# Question

How do I define the return type of an interface method to be another interface?

I'm new to interfaces and abstract classes. I want to create a couple of interfaces to define core methods and variables for the objects for a shopping cart system. Then I want to create abstract classes which implement the core functions. The idea is that they can be used by other classes in slightly different ways for different projects.

Here are my (cut-down) interfaces:

public interface ICart
{
...
List<ICartItem> CartItems { get; set; }
}

public interface ICartItem
{
int ProductId { get; set; }
int Quantity { get; set; }
}


And here is my abstract Cart class (again, only showing relevant lines) which implements ICart:

public abstract class Cart : ICart
{

private List<CartItem> _cartItems = new List<CartItem>();

public List<CartItem> CartItems
{
get
{
return _cartItems;
}
}
}


And my CartItem class which implements ICartItem:

public abstract class CartItem : ICartItem
{
...
}


When I try to compile the classes I get an error saying: 'Cart' does not implement interface member 'CartItems'. 'Cart.CartItems' cannot implement 'ICart.CartItems' because it does not have the matching return type of System.Collections.Generic.List<ICartItem>.

I thought that the idea here is that the interface can be implemented by a number of classes which perform the core functions in different ways and add new methods, etc. Why would my interface need to know what class is actually being used, just as long as that class actually implements the interface correctly?

Answer

You need to user generics in C# 2 to achieve that:

public interface ICart<T> where T : ICartItem
{
    // ...
    List<T> CartItems { get; set; }
}

public abstract class Cart : ICart<CartItem>
{
    // ...
    public List<CartItem> CartItems { get; set; }
}
Comments