Joe Doyle wrote:
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[].
--
Larry Lard
Replies to group please