I posted some sample code recently, for some tests with C# 4.0 dynamic. Now I’ve found a new interesting thing — perhaps this is also related to using beta 2 instead of the RC, again I’ll try this when I get around to it. The thing is, I have created my own dynamic object:
public class MyDynamicType : DynamicObject {
public override bool TryInvokeMember(InvokeMemberBinder binder,
object[] args, out object result) {
Console.WriteLine("TryInvokeMember {0}", binder.Name);
result = null;
return true;
}
public override bool TryGetMember(GetMemberBinder binder, out object result) {
Console.WriteLine( "TryGetMember " + binder.Name);
return base.TryGetMember(binder, out result);
}
}
Very simple. Now, you already know my little DoFall
helper function. I have this code in my main program:
dynamic myObject = new MyDynamicType();
myObject.Fall( );
DoFall(myObject);
Not surprisingly, this is the result:
TryInvokeMember Fall
TryInvokeMember Fall
Now I add my previous tests back into the main method, so I have this code altogether:
DoFall(new Leaf());
DoFall(new ExchangeRate());
DoFall(42);
dynamic myObject = new MyDynamicType();
myObject.Fall( );
DoFall(myObject);
What do you think the result is going to be??? Wrong! Here’s what I get:
Leaf is falling
Exchange rate is falling
Turns out 42 can't fall.
TryInvokeMember Fall
TryGetMember Fall
Turns out Dynamic.MyDynamicType can't fall.
Magic, eh? For a while there I thought there was some logic in this — after all, Fall
could conceivably be an element that has to be “accessed” first, before it can be “executed”, like a property that returns an anonymous function or similar. But since the behavior seems to change with the surrounding code in the caller method, it looks much more like a bug… hopefully just in beta 2.