tags:

views:

512

answers:

4

Apparently the following is valid in c# 4.0 regardless of the type of the object returned by GetADynamicThing()

dynamic d = GetADynamicThing();
d.Foo();

And if the runtime type of d does not contain a method Foo(), a RunTimeBinderException is thrown.

Will there be an easy way to determine if Foo() exists on d?

Otherwise, we're stuck doing old school reflection on the object, or relying on try-catch. Not sure I like either approach.

Update: So we have currently have 3 options:

  1. Reflection
  2. Catch Exception
  3. Hope GetADynamicThing() returns what you expect it to return

Number 3 seems to be the targeted usage of dynamic which in COM situations is great. The reason I asked the question originally was in response to doing something like this i.e. using methods some arbitrarily created object. This very much seems like the wrong situation to be using dynamic.

A: 

If there is no way to find out right now, I hope they do.

Maintenance nightmare

Fredou
-1, I don't believe you are right. The whole point of dynamic is that you don't necessarily know the exact type nor need to know at compile time - it is dynamically bound. If you do know the type, use object and a judicious cast or the type itself, rather than dynamic.
Jeff Yates
@Jeff, that type of thing remind me some nightmare I had with vb6 code. People will abuse.
Fredou
Of course people will abuse, just like people abuse extension methods, strings, IDisposable, and just about any other language feature. Abuse is no excuse for not giving people tools needed to get a job done.
Jeff Yates
+2  A: 

The whole point of the dynamic type is to assume member presence.

If you really need to know before you call the method use reflection or better yet create a concrete type the implements an interface that declares Foo(). I would contend that if you need to check if Foo() is a member of a dynamic type, then dynamic is the wrong choice for you. It sounds like you need static type checking.

Andrew Hare
+1  A: 

If your architecture is so open such that you have no idea what is being returned by GetADynamicThing then you should either catch the exception or use reflection somehow. However, in most scenarios, you will have a good idea of what you should be getting and can make some assumptions.

Jeff Yates
+3  A: 

The dynamic type is not meant to be a replacement for System.Object. If you have NO idea what is being returned, using System.Object or a concrete interface in your API is still a better approach than using dynamic, even in C# 4.

Dynamic is very useful if you know, basically, what you are returning. You should treat a member being missing (ie: Foo) as an exceptional case, in which case the exception is a reasonable way of handling this.

Reed Copsey