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) { } 
2

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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); } } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.