array conversion

S

Sankar Nemani

Why does the following code throw an exception?

object[] o = new object[2]{"sankar", "sankar2"};
string[] s;
s =(string[])o;


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).
 
J

Jon Skeet [C# MVP]

Sankar Nemani said:
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
:(
 
C

Cor Ligthert

Sankar,

I answered you in the VBlanguage group, where you left the documentation by
the way, in C# my answer would have been that it should be in my opinion.
object[] o = new object[2]{"sankar", "sankar2"};
string[] s;
s =(string[])o;

object[] o = new string[2]{"sankar", "sankar2"};
string[] s;
s =(string[])o;

And than some text however that you can read there.

Cor
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top