downcasting from a System.Array to an array of a specific type

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

I'm trying to do this-

....
void method1(System.Array arr)
{
// happen to know all elements in arr are int's

// this line throws an InvalidCastException
int[] intArr = (int[]) arr;
}

yes, it's asking a bit much to have it work with that simple of syntax, but
is there any way to downcast from a System.Array to a <specific type>[]
(e.g., int[]), as an alternative to creating a new specific type array, and
copying from the System.Array?
 
Do you really want to cast the array itself? Why not simply cast the
elements as you retrieve them.

Pete
 
Joe said:
I'm trying to do this-

...
void method1(System.Array arr)
{
// happen to know all elements in arr are int's

// this line throws an InvalidCastException
int[] intArr = (int[]) arr;
}

yes, it's asking a bit much to have it work with that simple of syntax, but
is there any way to downcast from a System.Array to a <specific type>[]
(e.g., int[]), as an alternative to creating a new specific type array, and
copying from the System.Array?

You should be able to see why this isn't possible. The fact that you
'happen to know all elements ... are ints' is what allows you to safely
do an Array.Copy into an int[]. If it *were* possible to somehow do
this cast, then picture this:

object[] arr = new object[] { 1,2,3 };
System.Array a = arr; // to hide its type from the compiler
int[] intarr;

// suppose this line worked:
intarr = (int[]) a;

arr[2] = new Hashtable();

// what is int[2] now??

Casting only makes sense when the thing actually *is* of the type you
are trying to cast to. Just because an array only contains ints, that
doesn't make it an int[].
 
Joe Doyle said:
void method1(System.Array arr)
{
// happen to know all elements in arr are int's

// this line throws an InvalidCastException
int[] intArr = (int[]) arr;
}

yes, it's asking a bit much to have it work with that simple of syntax, but
is there any way to downcast from a System.Array to a <specific type>[]
(e.g., int[]), as an alternative to creating a new specific type array, and
copying from the System.Array?

Where do you get the System.Array in the first place?
Do you really have an int[] or
do you have an object[] full of boxed ints?

Bill
 
Joe said:
I'm trying to do this-

...
void method1(System.Array arr)
{
// happen to know all elements in arr are int's

// this line throws an InvalidCastException
int[] intArr = (int[]) arr;
}

You will get an InvalidCastException if arr is *not* an int[]. Did you
check this?

Cheers,
 

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

Back
Top