Typecasting Arrays  
Author Message
NitinAgarwal





PostPosted: Visual C# Language, Typecasting Arrays Top

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



Visual C#4  
 
 
Mattias Sjogren





PostPosted: Visual C# Language, Typecasting Arrays Top

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



 
 
Maheswari





PostPosted: Visual C# Language, Typecasting Arrays Top

instead of "object[] objArray = (object[])obj;" use the following code

float[] test1 = (float[])obj;



 
 
NitinAgarwal





PostPosted: Visual C# Language, Typecasting Arrays Top

Hey thanks for your comments. Well I can typecast it to float[] instead of object[]. But the real issue is that type of array is also unknown till runtime. It can be float, int, double etc.
 
 
NitinAgarwal





PostPosted: Visual C# Language, Typecasting Arrays Top

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 objectIdea;

Array.Copy(test, objArray, i);

object obj = objArray;

object[] arr = (object[])obj;


 
 
Figo Fei - MSFT





PostPosted: Visual C# Language, Typecasting Arrays Top

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



 
 
Keith Rome





PostPosted: Visual C# Language, Typecasting Arrays Top

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