The following code throws an InvalidCastException.
public static MachineProductCollection MachineProductsForMachine(
MachineProductCollection MachineProductList, int MachineID)
{
return (MachineProductCollection)
MachineProductList.FindAll(c => c.MachineID == MachineID);
}
This surprises me since MachineProductCollection is merely a generic List of MachineProducts which is exactly what FindAll() should return. Here’s the full MachineProductCollection source code. You will note is merely a wrapper for List.
[Serializable]
public partial class MachineProductCollection :
List<MachineProduct>
{
public MachineProductCollection() { }
}
I resorted to the following which basically loops through the FindAll() result which is of type List and adds each item to my MachineProductCollection. Obviously, I don’t like the required iteration.
public static MachineProductCollection
MachineProductForMachine(MachineProductCollection
MachineProductList, int MachineID)
{
MachineProductCollection result =
new MachineProductCollection();
foreach (MachineProduct machineProduct in
MachineProductList.FindAll(c => c.MachineID == MachineID))
{
result.Add(machineProduct);
}
return result;
}
Documentation states an InvalidCastException is thrown when a failure occurs during an explicit reference conversion. Reference conversions are conversions from one reference type to another. While they may change the type of the reference, they never change the type or value of the conversion’s target. Casting objects from one type to another is a frequent cause for this exception.
Considering List is MachineProductCollection’s base, should this really be an InvalidCastException?