how to solve InvalidCastException

653 Views Asked by At

I am trying to get an subarray to convert to the type in 'parameterType' . 'para' is an array of objects. I am getting an invalid cast exception.

I am new to c# and not able to solve this.

 object[] param_values = new object[parameterType.Length];
 int k,q = 0;
 int size;
 foreach (ParameterInfo p in parameterType)
 {
     size = Marshal.SizeOf(p.ParameterType);
     object dest = para.Skip(k).Take(size).Cast<object>();
     param_values[q] = Convert.ChangeType(dest, p.ParameterType); // exception occurs here
     k = k + size;
     q++;
}
1

There are 1 best solutions below

1
On

You are selecting multiple objects that you are trying to cast.

object dest = para.Skip(k).Take(size).Cast<object>(); returns an IEnumerable<object> and you cannot cast/changetype it, for example, an Int32.

You might try this:

object[] param_values = new object[parameterType.Length];
int q = 0;
foreach (object p in para)
{
    param_values[q] = Convert.ChangeType(p, parameterType[q]); 
    q++;
}