While investigating how C# dynamic keyword works, I stumbled upon some weird behaviour. It almost looks like a bug, but it probably more likely there is a reason for the behaviour.
In the code below, there are two calls, one to obj1 and one to obj2, but only one of them executes correctly. It seems like the local variable type is the reason, but "Hello" should also be accessible from IDynamicTarget, because 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"
}
}
}