More odd behavior – DynamicObject this time

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.

2 Comments on More odd behavior – DynamicObject this time

  1. Have you looked at the generated IL. I bet you find the answer there. I expect that the DoFall method wraps your MyDynamicType in a dynamic object.

    Like

  2. Hi Steven,

    Yeah, I believe that – but I haven’t checked it. I lost interest in the exact reason when I saw that the behavior depends on a few lines of entirely unconnected code. I don’t expect this to be intended behavior anymore. Will keep this blog posted when I find out more.

    Like

Leave a Comment

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s