Reputation: 3025
My code is attempting to call multiple methods with a variable number of arguments using MethodInfo.Invoke but the call throws an ArgumentException
. What is causing this and how can I fix it?
The methods signature of the methods being called looks like this:
private static string MethodBeingCalled(params string[] args)
{
//do stuff
return stringToReturn;
}
The line of code that is calling these methods looks like this:
string valueReturned = method.Invoke(obj, new object[] { "01" }).ToString();
This line throws an ArgumentException:
Object of type 'System.String' cannot be converted to type 'System.String[]'.
When I change MethodBeingCalled to take a fixed list of arguments(ie: MethodBeingCalled(string arg)
) everything works fine.
Upvotes: 2
Views: 1218
Reputation: 1304
See this answer here . It checks for ParamArrayAttribute
present and passes values as array.
Upvotes: 1
Reputation: 2009
params is actually a workaround of the compiler. Behind, the real type of the parameter is an array. So when you do this : method.Invoke(obj, new object[] { "01" })
, that cannot work. You need to do this :
method.Invoke(obj, new object[] { new string[] {"01"} })
That should work.
Upvotes: 4