C # strange behavior

While researching how the C # keyword works, I came across some weird behavior. It almost seems like a mistake, but most likely there is a reason for the behavior.

There are two calls in the code below: one for obj1 and one for obj2, but only one of them executes correctly. It seems that the reason is the local type of the variable, but "Hello" should also be accessible from IDynamicTarget as it extends IDynamicTargetBase.

namespace DynamicTesting { interface IDynamicTargetBase { string Hello(int a); } interface IDynamicTarget : IDynamicTargetBase { } class DynamicTarget : IDynamicTarget { public string Hello(int a) { return "Hello!"; } } class Program { 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" } } } 
+7
c # dynamic dynamic-language-runtime
source share
1 answer

This seems to be a problem with the method overload problem.

Just change dynamic a = 123 to int a = 123 and your code will work. Also, if you change the method call to obj2.Hello((int)a); . Finally, enter the variable as DynamicTarget instead of IDynamicTarget , and it will work too!

Why? When you work with dynamic expressions, and there is more than an overload of a method for which invokation has dynamic arguments, the runtime will not be able to resolve the overload for the call, since the resolution of the method overload is based on the type and order of the arguments provided when the so-called method is called.

My assumption is a runtime overload error, when an interface also implements another interface, and the runtime seems to understand that there is no guarantee that the second interface will determine the overload of one of the other interfaces, which also implements, and this forces you to specify the actual type of argument (s) at compile time.

[...] but "Hello" should also be accessible from IDynamicTarget, because it extends IDynamicTargetBase.

It is available, but the runtime cannot decide how to provide method arguments ...

0
source share

All Articles