FaithN
FaithN

Reputation: 55

Reflection error: "parameter type mismatch"

I am trying to understand Reflection in c# and I am trying to get the following code to work. The first method (GetUserName) works but the second method (AddGivenNumbers) is giving me an exception error of "parameter type mismatch". I created a class library with the 2 methods and am trying to use reflection in main console application.

Class Library Code:

namespace ClassLibraryDELETE
{
    public class Class1
    {
        public string GetUserName(string account)
        {
            return "My name is " + account;
        }

        public int AddGivenNumbers(int num1, int num2)
        {
            return num1 + num2;
        }
    }
}

Code in my main console application:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Reflection;

namespace ConsoleApplicationDELETE_REFLECTION
{
    class Program
    {
        static void Main(string[] args)
        {
            Assembly assemblyInstance = Assembly.LoadFrom(@"C:\Users\xyz\Desktop\Debug\ClassLibraryDELETE.dll");
            Type Class1Type = assemblyInstance.GetType("ClassLibraryDELETE.Class1");
            object class1Instance = Activator.CreateInstance(Class1Type);
            MethodInfo getMethodFullName = Class1Type.GetMethod("GetUserName");
            string[] parameter = new string[1];
            parameter[0] = "John Doe";
            string userName = (string)getMethodFullName.Invoke(class1Instance, parameter);
            Console.WriteLine("User Name = {0}", userName);

            Assembly assemblyInstance2 = Assembly.LoadFrom(@"C:\Users\xyz\Desktop\Debug\ClassLibraryDELETE.dll");
            Type ClassType2 = assemblyInstance.GetType("ClassLibraryDELETE.Class1");
            object class1Instance2 = Activator.CreateInstance(ClassType2);
            MethodInfo getMethodFullName2 = ClassType2.GetMethod("AddGivenNumbers");
            //object[] parameters = new object[2];
            //parameters[0] = 8;
            //parameters[1] = 4;
            object[] args2 = new object[] { 1, 2 };
            object result = getMethodFullName.Invoke(class1Instance2, args2);
            Console.WriteLine("Sum of the two numbers is {0}", result);
            Console.ReadLine();
        }
    }
}

Upvotes: 1

Views: 935

Answers (1)

Jamiec
Jamiec

Reputation: 136074

You have a typo

object result = getMethodFullName.Invoke(class1Instance2, args2);

You should have been targeting getMethodFullName2, otherwise you're trying to execute the first function (which takes 1 argument) with 2 arguments.

Working example: http://rextester.com/WBFYB30834

Upvotes: 2

Related Questions