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>, to a MachineProductCollection even though MachineProductCollection inherits from List<MachineProduct>.
// Code complies and the invalid Cast results in // machineProducts being set to null instead of an // exception being thrown. MachineProductCollection machineProducts = MachineProductList.FindAll(c => c.MachineID == MachineID) as MachineProductCollection;
As statement in the above comment, the invalid cast is essentially masked due to the Safe Cast or the convert using the “as” operator. Alternative implementations, I believe, are more appropriate as an implicit conversion causes a pre-runtime, compilation error and a “traditional” cast throws an InvalidCastException at runtime, respectively:
// Compiler complains since it knows List<MachineProduct> can not // be converted to MachineProductCollection MachineProductCollection machineProducts = MachineProductList.FindAll(c => c.MachineID == MachineID); // Code compiles but a runtime InvalidCastException is thrown // since List<MachineProduct> can not be converted to // MachineProductCollection MachineProductCollection machineProducts = (MachineProductCollection) MachineProductList.FindAll(c => c.MachineID == MachineID);
I’m probably missing something but I can’t think of a scenario in which I would intentionally want to assign a null value if my cast is invalid. Why “swallow” the exception and work with bad data? It doesn’t make sense to me.
I’ve read that one should use the “is” operator in conjunction with the “as” operator. Basically, this ensures the conversion is valid before it is executed, but what is the point. Do more work to get the same lousy, invalid result?
// What is the point of this? MachineProductCollection machineProducts = null; if (MachineProductList.FindAll(c => c.MachineID == MachineID) is MachineProductCollection) { machineProducts = MachineProductList.FindAll(c => c.MachineID == MachineID) as MachineProductCollection; }
Perhaps I should have taken more CS classes in college…
Additional References: