Matias Cicero
Matias Cicero

Reputation: 26321

C# - How to use Reflection to invoke static method with variable number of parameters

I want to identify the following method via reflection:

String.Concat(params string[] args);

This is what I have tried:

MethodInfo concatMethod = typeof(string).GetMethod("Concat", new Type[] { typeof(string[]) });

The method is being identified correctly, but when I try to invoke it:

object concatResult = concatMethod.Invoke(null, new object[] { "A", "B" });

I get the following exception:

TargetParameterCountException: Parameter count mismatch.

Also note that I am passing null as the instance argument to the Invoke method, this is because the method is static and therefore an instance is not needed. Is this approach correct?

PS: I want to simulate the following call:

String.Concat("A", "B");

Upvotes: 2

Views: 1761

Answers (1)

Lee
Lee

Reputation: 144206

Each element of the input array is a parameter to the method. The overload of Concat you have takes a single string[] argument so you need:

object concatResult = concatMethod.Invoke(null, new object[] { new string[] { "A", "B" } });

Upvotes: 5

Related Questions