Hi,
I am facing some problem while typecasting arrays.
I have folowing line of code (test code)
// Define in one function that returns object (array of float, double, int etc.)
float[] test = new float[2];
test[0] = 1.1F;
test[1] = 2.2F;
object obj = test;// When I recieve this object back to caller fiunction I have to manipulate these individual elements
// So I typecasted this to object[]
object[] objArray = (object[])obj;
Now this line of code gives me run time error.
Is it that we can not type cast arrays
Thanks
Nitin

Typecasting Arrays
&#169&#59; Ţĩмό Şąļσмāĸ
I got the way to do it in C# but internal remains still opaque to meL
Excerpt from
http://msdn2.microsoft.com/en-us/library/system.array.aspx
“The Array.Copy method copies elements not only between arrays of the same type but also between standard arrays of different types; it handles type casting automatically.”
Line of code:
float[] test = new float[2];
test[0] = 1.1F;
test[1] = 2.2F;
int i = test.Length;
object[] objArray = new object
;
Array.Copy(test, objArray, i);
object obj = objArray;
object[] arr = (object[])obj;
Valery Zharkov
Joaquín Raya
Hi,
Why not use Generics in C#
For array use, use System.Collections.Generic.List<> or System.Collections.ArrayList who has already implemented the IList interface.
Thank you
Steve1999
The reason for this behavior is that arrays have a type themselves. object[] is not castable (up or down) to float[]. If that were allowed, then type verification could not be ensured. The only thing that can re-cast the array contents is the Array.Copy() function, which also performs type verification on each element.
HTH
Jamie Gordon
Not from an array of a value type to object[] you can't. That would require boxing of each element. Why don't you cast to float[] instead
karfast
instead of "object[] objArray = (object[])obj;" use the following code
float
[] test1 = (float[])obj;