How to pass an argument when invoking a method (reflection)?

I need to call a method, passing an int. using the following code I can fetch the method but not passing the argument. How to fix it?

dynamic obj;
obj = Activator.CreateInstance(Type.GetType(String.Format("{0}.{1}", namespaceName, className)));

var method = this.obj.GetType().GetMethod(this.methodName, new Type[] { typeof(int) });
bool isValidated = method.Invoke(this.obj, new object[1]);

public void myMethod(int id)
{
}
Jon Skeet
people
quotationmark

The new object[1] part is how you're specifying the arguments - but you're just passing in an array with a single null reference. You want:

int id = ...; // Whatever you want the value to be
object[] args = new object[] { id };
method.Invoke(obj, args);

(See the MethodBase.Invoke documentation for more details.)

Note that method.Invoke returns object, not bool, so your current code wouldn't even compile. You could cast the return value to bool, but in your example that wouldn't help at execution time as myMethod returns void.

people

See more on this question at Stackoverflow