Here is the sample code for the discussion (consider Reptile "is a" Animal and Mammal "is a" Animal too)
Animal[] reptiles = new Reptile[]
{ new Reptile("lizard"), new Reptile("snake") };
Animal[] animals = new Animal[]
{ new Reptile("alligator"), new Mammal("dolphin") };
try
{
Array.ConstrainedCopy(animals, 0, reptiles, 0, 2);
}
catch (ArrayTypeMismatchException atme)
{
Console.WriteLine('[' + String.Join<Animal>(", ", reptiles) + ']');
}
When I run this code I get a ArrayTypeMismatchException, with as comment
Array.ConstrainedCopy will only work on array types that are provably compatible, without any form of boxing, unboxing, widening, or casting of each array element. Change the array types (i.e., copy a Derived[] to a Base[]), or use a mitigation strategy in the CER for Array.Copy's less powerful reliability contract, such as cloning the array or throwing away the potentially corrupt destination array.
However when I look at MSDN I see this method also throws an InvalidCastException. The condition for throwing an InvalidCastException is:
At least one element in sourceArray cannot be cast to the type of destinationArray.
So I am stumped, how do you get an InvalidCastException out of this method, if as it states there can never be any casting of an array element?
reliablewhich I assume relates to the guarantees made. I suspect the underlying method can throw theInvalidCastExceptionbut not when thereliableparameter is true as in this case.reliableis false when using the basic copy command (so the same underlying method but with the boolean different). The basic copy will throw the InvalidCastException as you'd expect if you used that instead.Animalan interface whereMammalandReptileis implemented from or isAnimala base class that extends bothMammalandReptile?MammalextendsAnimaldirectly andReptileextendsAnimaldirectly. But please don't focus on this detail, at this point ANY information leading to the capture, dead or alive, of an InvalidCastException from from this method will be appreciated.