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?
Note: You also can use interface names as return types. In this case, the object returned must implement the specified interface.
To create an interface, you must write both the interface declaration and the interface body. The interfaceDeclaration declares various attributes about the interface such as its name and whether it extends another interface. The interfaceBody contains the constant and method declarations within the interface.
An interface can extend any number of interfaces but one interface cannot implement another interface, because if any interface is implemented then its methods must be defined and interface never has the definition of any method.
An interface, i.e., declared within another interface or class, is known as a nested interface. The nested interfaces are used to group related interfaces so that they can be easy to maintain. The nested interface must be referred to by the outer interface or class. It can't be accessed directly.
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; }
}
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