Neil
Neil

Reputation: 1299

c# dynamic object Runtime Type-Checking

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.

Upvotes: 1

Views: 3310

Answers (4)

Reed Copsey
Reed Copsey

Reputation: 564333

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.

Upvotes: 5

Jeff Yates
Jeff Yates

Reputation: 62367

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.

Upvotes: 1

Andrew Hare
Andrew Hare

Reputation: 351456

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.

Upvotes: 2

Fredou
Fredou

Reputation: 20090

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

Maintenance nightmare

Upvotes: -1

Related Questions