Re: Casting struct[] to object[]

Tech-Archive recommends: Repair Windows Errors & Optimize Windows Performance

From: Niki Estner (niki.estner_at_cube.net)
Date: 06/30/04


Date: Wed, 30 Jun 2004 23:45:09 +0200

First of all, conversion from struct to object isn't a cast. It's boxing.
Second, you don't want to cast the array reference you have to, say
System.Array or System.Object, you want to cast every item in the array.
That's more than a cast.
However, the .net language designers thought of that and build a method for
it: Array.Copy.

        object[] dest = new object[my_struct.Length];
        Array.Copy(my_struct, dest, my_struct.Length);

Copies (and casts) data from one array to another. Fine, isn't it?

Niki

"Fabrizio" <nospam@nospam.com> wrote in
news:d1DEc.28110$GQ3.718354@twister2.libero.it...
> Hi
> I cannot figure why it isn't possible to cast a struct array to an object
> array.
>
> I written a structure like this:
>
> public struct Test {
> private int TestA;
> private int TestB;
>
> public int A {
> get {return this.TestA;}
> }
> public int B {
> get {return this.TestB;}
> }
> public Test(int a, int b) {
> this.TestA=a;
> this.TestB=b;
> }
> }
>
> I have an array of Test struct values (Test[]):
> Test[] = new my_struct[2];
> my_struct[0] = new Test(1,2);
> my_struct[1] = new Test(2,3);
>
> but if I try to cast the structure array to the object:
> object[] dest = (object[])my_struct;
>
> the compiler tells me that it isn't possible to cast Test[] to object[],
> although it gives me no error if I cast a single Test struct value to
> object:
> object o = (object)my_struct[0];
>
> Moreover, if i change the struct declaration to a class declaration, no
> error occurs for a class array to an object array!
>
> Should I perform some casting operator overload in Test?
>
>
> TIA
> Fabrizio
>
>
>
>
>



Relevant Pages