-1

I've found lots of info on passing parameters to methods and found that having the method use params Object[] args to be a great (and sometimes only) way to do this.

i.e. sample method:

public void someMethod(params object[] args)
{
      //do something
}

But when passing the parameter object like this to a Com Method, it doesn't work:

object[] passParameters = new object[2];
passParameters[0] = "test1";
passParameters[1] = "test2";

//Calling method compiled with with CodeDom
MethodInfo method = classObject.GetType().GetMethod("someMethod");
object dynamicOutput = method.Invoke(classObject, passParameters);

For it to work, I have found that I need to pass the parameter object as a new Object:

object dynamicOutput = method.Invoke(classObject,(new object[] { passParameters });

Can anyone please explain to me why I need to do this and what the reasoning is behind it? Thanks.

Joe
  • 616
  • 2
  • 12
  • 27

2 Answers2

0

They don't. You can just use them as

someMethod("test1", "test2", ... )

BUT. If you're creating an array beforehand, it has to be passed differently, as you encountered

Hexo
  • 518
  • 7
  • 21
0

I've come to realise that the original passParameters object in the example contains two elements, as we know:

passParameters[0] = "test1";
passParameters[1] = "test2";

However, when the array is passed to the Com method, it requires being passed as so:

new object[] { passParameters })

My understanding of this is, that it creates a new object array which has put the existing 'passParameters' array into its first element [0] (effectively creating a new 2d array):

passParameters[0][0] = "test1";
passParameters[0][1] = "test2";

The method MethodInfo class in my question, required a single object passed to the Invoke method, which meant that the original 'passParameters' object with its two elements had too many arguments. By passing it inside a new object, this passes all of the elements as a single object, but containing an array of those parameters.

Joe
  • 616
  • 2
  • 12
  • 27