0

I am invoking a method with parameter using reflection (dynamic to be precise). No problem with the invokation when parameter of the method and arguments passed match at compile time; but if i use a base type (in the signature, at runtime types always match), event if a runtime parameter match i get error (at runtime).

Example below :

public class WorkerAbstraction 
{
    object _actualWorker  = null;

    public WorkerAbstraction (object actualWorker)
    {
         _actualWorker = actualWorker;
    }

    public void DoWorkAbs ( AbstractBaseClass args )
    {
         ((dynamic)_actualWorker).DoWork (args); //--> here is where the exception is rised
    }
}

public class ActualWorker<T> where T : AbstractBaseClass 
{
    public void DoWork ( T args )
    {
         ...
    }
}

public class Person : AbstractBaseClass { ... }

Now if i test the code above that way :

WorkerAbstraction wab = new WorkerAbstraction ( new ActualWorker<Person> () );
Person person = new Person();

wab.DoWorkAbs (person);

Then i get that exception :

The best overloaded method match for 'ActualWorker.DoWork(Person)' has some invalid arguments.

I have checked at runtime, when exception is rised (in DoWorkAbs) : _actualWorker is ActualWorker args is Person

Then i have modified the code and checked it again :

    public void DoWorkAbs ( AbstractBaseClass args )
    {
         ((dynamic)_actualWorker).DoWork ((Person)args); //--> that explicit cast solve the problem
    }

What i don't understand is the origin of the problem. Ok that aproach is not 100% safe, but in my case in both scenario object and parameter are correct at runtime.

So what's going on?

-----Edit : itegrated a working example

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

namespace TestReflection
{
    class Program
    {
         static void Main(string[] args)
         {
              Person person = new Person() { Name = "Michelle" };
              WorkerAbstraction wab = new WorkerAbstraction(new ActualWorker<Person>());


        wab.DoWorkAbs(person);
        Console.ReadKey();
    }
}

public class WorkerAbstraction
{
    object _actualWorker = null;

    public WorkerAbstraction(object actualWorker)
    {
        _actualWorker = actualWorker;
    }

    public void DoWorkAbs(AbstractBaseClass args)
    {
        ((dynamic)_actualWorker).DoWork(args); // --> raise exception
        //((dynamic)_actualWorker).DoWork((Person)args); // --> working fine
    }
}

public class ActualWorker<T> where T : AbstractBaseClass
{
    public void DoWork(T args)
    {
        args.SayHello();
    }
}

public class Person : AbstractBaseClass
{
    public Person()
    {
    }

    public string Name { get; set; }

    public override void SayHello()
    {
        Console.WriteLine ($"{this.Name} say hello.");
    }
}

public abstract class AbstractBaseClass 
{
    public abstract void SayHello();
}

}

2
  • @JonSkeet sure, i integrate my question ASAP
    – Skary
    Jan 14, 2021 at 14:06
  • It's worth noting that this isn't so much "through reflection" as "through dynamic typing" - it's not the reflection part that's failing, it's the dynamic binding part.
    – Jon Skeet
    Jan 14, 2021 at 14:16

1 Answer 1

7

The problem is that the compiler remembers the compile-time types of the arguments to dynamic binding. The compile-time type of args is AbstractBaseClass, so that's what's used during the dynamic look-up. You're only being dynamic on the target of the call, not in the arguments.

If you want the binding to be dynamic in the arguments as well, you need to do that separately. For example, this doesn't throw an exception, because the overload resolution "knows" that the argument type is dynamic too:

public void DoWorkAbs(AbstractBaseClass args)
{
    dynamic target = _actualWorker;
    dynamic dynamicArgs = args;
    target.DoWork(dynamicArgs);
}

The problem can be demonstrated rather more simply though, without generics or abstract classes:

public class Test
{
    public void M(string x)
    {
    }
    
    static void Main()
    {
        dynamic target = new Test();
        string s = "text";
        // Succeeds; it's looking for M(string) (or a compatible method)
        // at execution time, based on the compile-time type of s
        target.M(s);
        
        // Succeeds; it will look for M(string) (or a compatible method)
        // at execution time, based on the execution-time type of the
        // value of d.
        dynamic d = "text";
        target.M(d);
                        
        object o = "text";
        // Fails; it's looking for M(object) (or a compatible method)
        // at execution time, based on the compile-time type of o.
        target.M(o);
    }
}

In terms of how you deal with this, I'd strongly recommend trying to avoid dynamic typing here, if you possibly can.

1
  • thanks a lot super clear in an explanation about an aspect of the framework that i don't know.
    – Skary
    Jan 14, 2021 at 14:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.