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 FindAll() returns. Here’s the full MachineProductCollection source code:
[Serializable] public partial classMachineProductCollection : List<MachineProduct> { public MachineProductCollection() { } }
I resorted to the following which basically loops through the resulting List<MachineProduct> and adds them 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<MachineProduct> is MachineProductCollection’s base, should this really be an InvalidCastException?
That is odd. Generic types are odd – I just learned that you have to call Type.MakeGenericType() to convert between “normal” and generic types when creating an object, for instance.
Given that MachineProductCollection is just wrapping List, why create an explicit collection? Why not just use List, and you wouldn’t need to cast?
I may take your suggestion and fallback to simply using List rather than using a simple custom collection since I’m basically forced to do so within my “lookup” functions anyway. It’s merely a pattern I tend to follow. Perhaps it is time for me to break the rules. Thank Jon.
[...] Views I’m not sure I can come up with a good argument to ever use Safe Casting. Per my earlier post, I’m not able to convert the result of the following Predicate, List<MachineProduct>, [...]
[...] el mejor uso del Kindle. De la misma manera, cierta parte de esta comunidad ha desarrollado un firmware alternativo, o se ofrecen gratis o venden aplicaciones (bloc de notas, traductores, …) que quizá [...]