0

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)
{
}
Nikhil Agrawal
  • 47,018
  • 22
  • 121
  • 208
GibboK
  • 71,848
  • 143
  • 435
  • 658

2 Answers2

5

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.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
0

Just pass an object with the invoke method

namespace test
{
   public class A
   {
       public int n { get; set; }
       public void NumbMethod(int Number)
       {
            int n = Number;
            console.writeline(n);
       }
    }
}
class MyClass
{
    public static int Main()
    {
        test mytest = new test();   
        Type myTypeObj = mytest.GetType();    
        MethodInfo myMethodInfo = myTypeObj.GetMethod("NumbMethod");
        object[] parmint = new object[] {5};
        myMethodInfo.Invoke(myClassObj, parmint);
    }
 }