.NET Casting Generic List

By : Josh
Source: Stackoverflow.com
Question!

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);
By : Josh


Answers

An alternative solution that also works for .NET 3.5

List<IShipMethod> shipMethods = GetForShipWeight(orderItems).ConvertAll(sm => sm as IShipMethod);
By : Bigjim


Actually, you can solve this by making GetForShipWeight a generic function:

public interface IPackable { double Weight { get; } }
public interface IShipMethod { }

public class OrderItem : IPackable { }

public List<IShipMethod> GetForShipWeight<T>(List<T> packages) where T : IPackable
{
    List<IShipMethod> ship = new List<IShipMethod>();
    foreach (IPackable package in packages)
    {
        // Do something with packages to determine list of shipping methods
    }
    return ship;
}
public void Test()
{
    List<OrderItem> orderItems = new List<OrderItem>();
    // Now compiles...
    List<IShipMethod> shipMethods = GetForShipWeight(orderItems);
}
By : Zarigani


This video can help you solving your question :)
By: admin