Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does dynamic binding fail when using interface inheritance?

Tags:

In C#, please does anyone know why I can't do the following? (specifically the line marked 'NOT fine!' below)

interface A {     void Add(dynamic entity); }  interface B : A {}  class C : B {     public void Add(dynamic entity)     {         System.Console.WriteLine(entity);     } }  class Program {     static void Main(string[] args)     {         B b = new C();         dynamic x = 23;         b.Add(23);        // fine         b.Add((int)x);    // fine         (b as A).Add(x);  // fine         //b.Add(x);       // NOT fine!     } } 

I have absolutely no problems if the call isn't dynamically-bound, or if I explicitly cast to the interface at the root of the hierarchy, but the dynamically-bound call gives me:

Unhandled Exception: Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: No overload for method 'Add' takes '1' arguments    at CallSite.Target(Closure , CallSite , B , Object )    at System.Dynamic.UpdateDelegates.UpdateAndExecuteVoid2[T0,T1](CallSite site, T0 arg0, T1 arg1)    at Program.Main(String[] args) in C:\Users\Stuart\Documents\Visual Studio 2010\Projects\CSharp Testbed\Program.cs:line 218 
like image 705
Stuart Golodetz Avatar asked Mar 10 '12 17:03

Stuart Golodetz


People also ask

What is Dynamic binding in object oriented programming?

Dynamic binding refers to linking a procedure call to code that will execute only once. The code associated with the procedure is not known until the program is executed, which is also known as late binding. Examples.

What is Dynamic binding association?

“Dynamic” means “run time”, and “binding” means “association”. So the term dynamic binding indicates run time association of objects by java virtual machine. Here we will see how Java achieves dynamic binding in run time, which means before the code's final running but after compilation.

What do you mean by dynamic binding explain?

Dynamic binding or late binding is the mechanism a computer program waits until runtime to bind the name of a method called to an actual subroutine. It is an alternative to early binding or static binding where this process is performed at compile-time.

What is dynamic binding in polymorphism?

Introduction. Polymorphism allows an object to take multiple forms – when a method exhibits polymorphism, the compiler has to map the name of the method to the final implementation. If it's mapped at compile time, it's a static or early binding. If it's resolved at runtime, it's known as dynamic or late binding.


1 Answers

Looking on Microsoft Connect it's filed as a bug - Dynamic runtime fails to find method from a base interface during runtime

like image 129
Luke Forder Avatar answered Sep 20 '22 18:09

Luke Forder