Reflection with array

  • Thread starter Thread starter Wernfried Schwenkner
  • Start date Start date
W

Wernfried Schwenkner

I want to deserialize a file. In one ofe my classes I have an array
like:

public class MyClass
{
public MyArray[] theArray;
}

i.e. an arry of an own defined class. While reading the file I only know
the dimension on the end of reading, so I keep the array elements in an
ArrayList "records". At the end I "only" have to assign the ArrayList to
the Array-field "theArray". And there is my problem.

arrayField.FieldType shows "MyArray[]", this is correct for me. If I try
with

arrayField.SetValue(records.ToArray(), instanceOfMyClass);

to assign the Array I get the error message that the objecttype can't be
converted to the destination type.
That's right, the object type is "object[]" and the destination type is
"MyArray[]".

How can I do the typecast at runtime?
Or is there another way to do this?
 
Hi Wernfried,

Before digging more deeply into this.

Are you sure that the invalid cast is because of the arrays
arrayField.SetValue(records.ToArray(), instanceOfMyClass);

AFIK in FiledInfo.SetValue first comes the object which field you set and
then the value of the field. So I believe you should switch the paramers

arrayField.SetValue(instanceOfMyClass, records.ToArray());

Try that and tell if the probles is still there

--
HTH
Stoitcho Goutsev (100) [C# MVP]


Wernfried Schwenkner said:
I want to deserialize a file. In one ofe my classes I have an array
like:

public class MyClass
{
public MyArray[] theArray;
}

i.e. an arry of an own defined class. While reading the file I only know
the dimension on the end of reading, so I keep the array elements in an
ArrayList "records". At the end I "only" have to assign the ArrayList to
the Array-field "theArray". And there is my problem.

arrayField.FieldType shows "MyArray[]", this is correct for me. If I try
with

arrayField.SetValue(records.ToArray(), instanceOfMyClass);

to assign the Array I get the error message that the objecttype can't be
converted to the destination type.
That's right, the object type is "object[]" and the destination type is
"MyArray[]".

How can I do the typecast at runtime?
Or is there another way to do this?
 
arrayField.SetValue(instanceOfMyClass, records.ToArray());

Try that and tell if the probles is still there
Thanks. This was the problem. I certainly got confused with my variabale
names and missed the order.
 
Back
Top