I'm getting Parameter count mismatch exception:
Getting Unhandled Exception: System.Reflection.TargetParameterCountException: Parameter count mismatch.
Code:
class Program
{
public static void Main()
{
ArrayList CustomerList = new ArrayList();
CustomerList.Add("Robinson");
CustomerList.Add("Pattison");
CustomerList.Add("Todd");
object[] obj = (object[])CustomerList.ToArray(typeof(object));
Assembly executingAssembly = Assembly.GetExecutingAssembly();
Type customerType = executingAssembly.GetType("LateBinding.Customer");
object customerInstance = Activator.CreateInstance(customerType);
MethodInfo method = customerType.GetMethod("printCustomerDetails");
string customerObject = (string)method.Invoke(customerInstance, obj);
Console.WriteLine("Value is : {0}", customerObject);
}
}
public class Customer
{
public string printCustomerDetails(object[] parameters)
{
string CustomerName = "";
foreach (object customer in parameters)
{
CustomerName = CustomerName + " " + customer;
}
return CustomerName.Trim();
}
}
The issue is here:
string customerObject = (string)method.Invoke(customerInstance, obj);
...and the method:
public string printCustomerDetails(object[] parameters)
The input parameters (second) argument of this MethodInfo.Invoke(...)
overload is an array of arguments, and your printCustomerDetails
method has one argument which is an array of objects object[]
, so you need to call Invoke
this way:
method.Invoke(customerInstance, new [] { obj });
Don't use ArrayList
, it's from the .NET 1.x days. Since .NET 2.0, you need to use generic collections from the System.Collections.Generic
namespaces (f.e. List<T>
, HashSet<T>
, Queue<T>
...)
And if you need to create the array dynamically, I would suggest you that you should use List<object>
instead of the outdated ArrayList
to get full LINQ and LINQ extension methods support, and other improvements on list-type collections on newer generic lists since .NET 2.0 (old days too! Now we're in .NET 4.5).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With