GojiraDeMonstah GojiraDeMonstah - 1 year ago 62
C# Question

Why does Method Invoke fail with argument exception?

Consider this code sample from a WinForms app:

public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)
{
object[] parms = new object[1];
parms[0] = "foo";

DoSomething(parms);
}

public static string DoSomething(object[] parms)
{
Console.WriteLine("Something good happened");
return null;
}
}


It works as expected, when you click button1 it prints "Something good happened" to the console.

Now consider this code sample, which is the same except that it invokes
DoSomething
using reflection:

public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)
{
object[] parms = new object[1];
parms[0] = "foo";

System.Reflection.MethodInfo mi = typeof(Form1).GetMethod("DoSomething");
mi.Invoke(null, parms);

}

public static string DoSomething(object[] parms)
{
Console.WriteLine("Something good happened");
return null;
}
}


It throws an
System.ArgumentException
on the line
mi.Invoke(null, parms)
(Object of type 'System.String' cannot be converted to type 'System.Object[]'.)

parms is clearly an object array, and DoSomething's method signature is clearly expecting an object array. So why is invoke pulling the first object out of the array and trying to pass that instead?

Or is something else going on that I'm not understanding?

Answer Source

MethodInfo.Invoke is expecting an object array, where each object in the object array corresponds to an argument to the method. The first argument in the object array is the first argument, the second object in the array the second method, etc.

Since you want the first argument to your method to be an object[], you need to ensure that the first object in the object array you pass to MethodInfo.Invoke is an object array that represents the array that DoSomething should use.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download