Member Exists – Dynamic C# 4.0

I have been using the dynamic keyword a little bit in C# and I have recently run into a small problem and I have been trying to figure out the most elegant way to resolve it. The problem is, when you try to invoke a member that does not exist on a dynamic object it throws an exception, there is no easy way to detect if the member exists built-in to accommodate this.

For example what I would really like is an ‘exists’ keyword, something like:

dynamic instance = new { Foo = "Hello World!" };
if (exists(instance.Foo))

But there appears to be no magic ‘exists’. Turns out the only way to do this is with reflection. So I created some helper extension methods to enable the following example:

object instance = new { Foo = "Hello World!" };

if (instance.Reflection().Exists().Foo)
    string value = instance.Reflection().Call().Foo;

Interestingly enough the Foo in this case is a call to a DynamicObject I created that can intercept calls to members and returns a bool if they exist, never calling them. The Reflection().Call() simply casts any object into a dynamic object for dynamic calling.

I also found out that you can’t use the dynamic Type as the first parameter in an extension method. Dynamic objects and extension methods don’t really play together very nicely.

Download the full example here:

Author: justinmchase

I'm a Software Developer from Minnesota.

3 thoughts on “Member Exists – Dynamic C# 4.0”

Drop a brain bomb

Please log in using one of these methods to post your comment: Logo

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

Google photo

You are commenting using your Google 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 )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.