Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting Unhandled Exception: System.Reflection.TargetParameterCountException: Parameter count mismatch

Tags:

c#

.net

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();
        }
    }
like image 743
Bhuwan Pandey Avatar asked May 31 '15 12:05

Bhuwan Pandey


1 Answers

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 });

Advice about ArrayList is outdated

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).

like image 83
Matías Fidemraizer Avatar answered Sep 24 '22 22:09

Matías Fidemraizer