Sankar Nemani <sn*****@nospamlumedx.com> wrote:
Why does the following code throw an exception?
object[] o = new object[2]{"sankar", "sankar2"};
string[] s;
s =(string[])o;
Because you haven't created a string array. You've created an object
array and populated it with strings. There's a big difference.
The C# language spec says something different on MSDN:
For any two reference-types A and B, if an implicit reference conversion
(Section 6.1.4) or explicit reference conversion (Section 6.2.3) exists from
A to B, then the same reference conversion also exists from the array type
A[R] to the array type B[R], where R is any given rank-specifier (but the
same for both array types).
This is interesting - it's okay at compile time because of that, but
it's not okay at runtime. What you've done is the equivalent of:
object o = new object();
string s = (string) o;
The explicit conversion is okay at compile time because of the first
listed explicit reference conversion. However, it's not valid at
runtime. The spec doesn't make this clear at all, as far as I can see
:(
--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too