MethodInfo.Invoke TargetException

I've an Issue with System.Reflection, when I call MethodInfo.Invoke method it gaves me the TargetException exception that says: Object does not match with target, Here the code:

object[] parms = new object[] { path };

Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
Type gameType = null;

foreach (Assembly asm in assemblies)
{
    string asmName = asm.GetName().Name;

    if (asmName == "Tester")
    {
        gameType = asm.GetType("Tester.Main");
        break;
    }
}

var game = Convert.ChangeType(GameInstance, gameType);
Type delegateType = game.GetType().GetEvent("gameVideoLoader").EventHandlerType;

MethodInfo method = delegateType.GetMethod("Invoke");
method.Invoke(game,  parms); // Here the exception

Any Idea? PS: game object is correctly assigned so it's not null

Jon Skeet
people
quotationmark

You're trying to call the delegate's Invoke method, but on a Tester.Main instance. That's just wrong - because the Tester.Main instance isn't an instance of the appropriate delegate.

If you're trying to actually raise the gameVideoLoader event, then that's a different matter... and something that you shouldn't be doing anyway. The purpose of events is to allow clients to subscribe and unsubscribe handlers - the object itself should be responsible for raising the event. You may be able to find an underlying field which is used to implement the event, get the value of that field and invoke the delegate - but I'd strongly advise against it. You're basically going against the design of events at this point.

people

See more on this question at Stackoverflow