Reputation: 7525
I have this class:
using System.Linq;
namespace TestNamespace {
public class Program {
public static void Main(string[] args) {
//does stuff
}
}
}
I am loading the above assembly and want to invoke the method with a string array parameter.
This gives me a null exception:
private static object[] parameters = new object[1];
string[] pa = { "1", "2" };
parameters[0] = pa;
//Creating target and other code
bool retVal = (bool)target.Invoke(null, parameters);
Any thoughts? Thanks
Upvotes: 0
Views: 5153
Reputation: 241641
Where's the NullReferenceException
. Are you sure that you're reflecting the MethodInfo
correctly and that target
is not null
? That's my suspicion as to what's really going on here. If there were a NullReferenceException
being thrown in the method, it would be wrapped in a TargetInvocationException
and thus I suspect the NullReferenceException
is because target
is null.
To be clear, here's how you load and invoke the method:
var target = typeof(Program)
.GetMethod("Main", BindingFlags.Public | BindingFlags.Static);
bool retVal = (bool)target.Invoke(null, new object[] { pa });
The parameters
parameter to MethodInfo.Invoke
is an object[]
with the same number, order and types of the parameters for the method being invoked. In your case, you have a single parameter of type string[]
. Thus, the object[]
parameter to MethodInfo.Invoke
should be an array with one element, and that element is an instance of string[]
. That is what I have accomplished with the syntax above.
Upvotes: 4