Reputation: 20626
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
Upvotes: 25
Views: 1580
Reputation: 1189
Looking on Microsoft Connect it's filed as a bug - Dynamic runtime fails to find method from a base interface during runtime
Upvotes: 12
Reputation: 6026
It looks like the multiple layers of interface inheritance are doing in the passing of a dynamic type variable. It's definitely tripping up the run time binding.
At this point if you're looking to get it to work a possible workaround is:
dynamic x = 23;
b.Add((object)x);
dynamic y = "Hello, World!";
b.Add((object)y);
Since dynamic is seen as object by the IL, so casting everything explicitly to type object will get this to work for you.
Upvotes: 0