Reflection - passing parameters to an invoked function

Hallo,

I’m playing around with reflection and learning the ropes, as it were. I’m trying to invoke a function using reflection, as below:

ParameterInfo[] parameters = methodInfo.GetParameters ();
if (parameters.Length == 0) {
		result = methodInfo.Invoke (comp, null);
} else {
		object[] parametersArray = args.Split ('|').Select (str => str.Trim ()).ToArray ();
		result = methodInfo.Invoke (comp, parametersArray);
}

What this aims to do is call a function without parameters if no arguments are specified, or call one WITH parameters if arguments are specified (as a string, delimited with | symbols.)

If arguments are specified, the args string is split by the | symbol into parametersArray and passed to the invoked function as above.

The problem I’m getting is that the last line of code, where the function is invoked, is generating an error - ArgumentException: failed to convert parameters.

Is this because I am passing parametersArray, which is a string/object, to a function (for testing purposes) that needs a boolean?

The code works fine for a function requiring a single string parameter…

When the function requires a bool parameter you need to invoke it with an array containing one bool variable. Passing a string array won’t work if it expects a bool value (failed to convert means can’t use string where bool is required here).

Hey - I’m having a similar problem, but these answers don’t work for me. Here’s my code:

I’m calling this:
info.Invoke(methodInfo[0], new object { args });

On this:
void Equip(object args)
{

}
And I get an ArgumentException: failed to convert parameters error. methodInfo is a string array. The [0] element is Equip, and args is an object array.