4

I've searched a few different posts about a similar issue but none seem to solve my particular issue (though I believe they can't be far off).

The below link is the closest version to my problem

"Object does not match target type" when calling methods using string in C#

The only difference between my issue and the one in the link is that I am calling a generic method.

When I make my call I get the error "Object does not match target type” but the types, form what I can tell definitely match. Here is sample code for which I have reproduced my problem.

Any help would be appreciated

class Program
{
    static void Main(string[] args)
    {
        var obj = new SerializeObject();
        var serializer = new Serializer();


        var serialiserType = serializer.GetType();
        MethodInfo method = serialiserType.GetMethod("Deserialize");
        if (method == null)
        {
            return;
        }

        var t = obj.GetType();
        MethodInfo genericMethod = method.MakeGenericMethod(t);
        var tmp = genericMethod.Invoke(obj, new object[] { "Test" }); //error here
    }
}

public class Serializer
{
    public T Deserialize<T>(string value) where T : new()
    {
        return new T();
    }
}

public class SerializeObject
{

}
Lord Byron
  • 167
  • 1
  • 2
  • 11
  • I would try storing the string in a variable first and then invoking the method (i.e. replace "Test" with a String variable name) disregard if you've already tried that. Beyond that I can't find anything big thats wrong – Redacted Sep 20 '18 at 16:36

1 Answers1

4

The documentation states that the first parameter obj must be the instance you wish to call the reflected method on:

obj Object

The object on which to invoke the method or constructor. If a method is static, this argument is ignored. If a constructor is static, this argument must be null or an instance of the class that defines the constructor.

As such, I would change the call to the following:

var tmp = genericMethod.Invoke(serializer, new object[] { "Test" });
Kzryzstof
  • 7,688
  • 10
  • 61
  • 108