6

Can you please explain the behavior for this code:

namespace DynamicTesting
{
    public interface IDynamicTargetBase
    {
        string Hello(int a);
    }

    public interface IDynamicTarget : IDynamicTargetBase
    {
    }

    public class DynamicTarget : IDynamicTarget
    {
        public string Hello(int a)
        {
            return "Hello!";
        }
    }

    public class Program
    {
        public static void Main(string[] args)
        {
            dynamic a = 123;

            IDynamicTargetBase obj1 = new DynamicTarget();
            obj1.Hello(a);  // This works just fine

            IDynamicTarget obj2 = new DynamicTarget();
            obj2.Hello(a); // RuntimeBinderException "No overload for method 'Hello' takes '1' arguments"
        }
    }
}

The result is:

[Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: No overload for method 'Hello' takes '1' arguments] at CallSite.Target(Closure , CallSite , IDynamicTarget , Object ) at System.Dynamic.UpdateDelegates.UpdateAndExecuteVoid2[T0,T1](CallSite site, T0 arg0, T1 arg1) at DynamicTesting.Program.Main(String[] args) :line 30

If I use int instead of dynamic then it's working fine. I cannot get why it's not working. Do you have any ideas?

Try it on your own: https://dotnetfiddle.net/55ZMAG

Boann
  • 48,794
  • 16
  • 117
  • 146
JeloneK
  • 249
  • 2
  • 11
  • 3
    Bizarre. Looks like a bug to me. – Jon Skeet Sep 24 '18 at 17:00
  • Interestingly, even when the argument type is changed to `dynamic` in the interface and the class, [the error still happens...](https://dotnetfiddle.net/CKqsHc) – Zohar Peled Sep 24 '18 at 17:06
  • looks like the CLR can't find the method because it's not declared on `IDynamicTarget`. If a method is declared on the base class it works fine. – Selman Genç Sep 24 '18 at 17:09
  • Is this possibly a similar problem like in the following question? https://stackoverflow.com/questions/3071634/strange-behaviour-when-using-dynamic-types-as-method-parameters – bassfader Sep 24 '18 at 17:14

0 Answers0