Can someone explain to me why in .NET 2.0 if I have an interface, IPackable and a class that implements that interface OrderItem, when I have a method that takes in a List<IPackable>, passing in a list of List<OrderItem> does not work?
Does anyone know how I could accomplish this functionality?
Code:
public interface IPackable { double Weight{ get; } } public class OrderItem : IPackable public List<IShipMethod> GetForShipWeight(List<IPackable> packages) { double totalWeight = 0; foreach (IPackable package in packages) { totalWeight += package.Weight; } }
The following code does not work.
List<OrderItem> orderItems = new List<OrderItem>(); List<IShipMethod> shipMethods = GetForShipWeight(orderItems);
The feature is called covariance/contravariance and will be supported in c# 4.0. You can read about it here: http://blogs.msdn.com/ericlippert/archive/tags/Covariance+and+Contravariance/default.aspx