eric.dennison@gmail.com wrote:
[color=blue]
> In the sample below:
>
> testClass is derived from object.
>
> We can cast object to testClass, no problem
> We can cast testClass[] to object[] no problem
> Compiler is ok with cast object[] to testClass[] but fails at runtime.[/color]
This behaviour of the .NET runtime, where T and S are types and S is a
subtype of T, where S[] can be cast to T[], seems to have been
introduced solely for compatibility with the Java language. It's
important to point out that it involves polymorphism. That is, S[]
stored in a variable of type T[] is *still*, at runtime, of type S[].
This becomes apparent when a third type, U, also derived from T, is
stored at runtime into an S[] which is being referred, polymorphically,
through a value of type T[]. (It causes a runtime exception.)
Basically, every store and load to and from an array of a reference type
is actually a virtual method call which uses dynamic dispatch based on
the runtime type of the array value.
For example:
---8<---
class App
{
static void Main()
{
string[] foo = { "a", "b" };
object[] bar = foo;
bar[0] = new App(); // Throws exception at runtime,
// because the object referred to by bar is not an object[]
// but is in fact a string[], which can't store App instances.
// That's why you can't cast an object[] value to string[],
// even if it only contains strings. It has to be a string[]
// value to begin with, when it was constructed.
}
}
--->8---
[color=blue]
> Why?[/color]
Your code tries to cast an object[] to a testClass[], but an object[] is
*not* a testClass[], even if all it contains is values
assignment-compatible with variables of type testClass[].
-- Barry
--
http://barrkel.blogspot.com/