Callum
Callum

Reputation: 3381

C# Reflection error

I'm a newbie when it comes to reflection and at the moment it all seems rather confusing so forgive me if some of your replies appear to confuse me a little more!!!

I'm currently trying to write a small script that will clone data held in one data table based on a value and then reinsert said data into the same table, albeit with an amended ID. I am trying to currently use reflection as I need to do this for multiple tables and do not wish to code out an excessive amount of clauses for countless number of tables.

The Code I have written so far for the reflection method is as follows:

public static void CopyData(object sourceObject, object targetObject) 
{
    object[] value = new object[1];
    object[] param = new object[0];

    foreach (PropertyInfo propertyInfo in sourceObject.GetType().GetProperties())
    {
        PropertyInfo targetPropertyInfo = targetObject.GetType().GetProperty(propertyInfo.Name);
        if (targetPropertyInfo.CanWrite && targetPropertyInfo.CanRead)
        {
            value[0] = propertyInfo.GetValue(sourceObject, BindingFlags.Public, null, null, null);
            targetPropertyInfo.SetValue(targetObject, value, null);
        }
    }
}

Now I currently have no problem passing the data I need into this class, HOWEVER I am getting thrown the following error:

Object of type 'System.Object[]' cannot be converted to type 'System.Int32'.

I believe this had to do with Integer fields used to identify links within the data. It is important that I keep these intact for processing later on down the line.

Can someone please point me in the right direction of a way to solve this issue????

Many thanks

Upvotes: 0

Views: 1249

Answers (1)

Chris
Chris

Reputation: 27627

I assume the error is thrown on this line:

targetPropertyInfo.SetValue(targetObject, value, null);

In this line value is an object array. I assume it should be an int32. Do you in fact mean to do this:

targetPropertyInfo.SetValue(targetObject, value[0], null);

This would be writing the value you just got out of the other object.

Upvotes: 2

Related Questions