Member Exists – Dynamic C# 4.0

by justin 2. July 2009 02:45

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))
{
    Console.WriteLine(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;
    Console.WriteLine(value);
}

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:

Tags: , ,

C# | .NET | dynamic

Comments

4/16/2010 10:37:26 AM #

pingback

Pingback from topsy.com

Twitter Trackbacks for
        
        Member Exists – Dynamic C# 4.0
        [justnbusiness.com]
        on Topsy.com

topsy.com |

5/24/2010 4:14:54 AM #

pingback

Pingback from 344.an74.com

200sx Bus, Replacement Keys Nissan 200sx - 344.an74.com

344.an74.com |

Comments are closed

About Me

sweetest hat ever

I'm a software developer from Minnesota and this blog largely focuses on various technical concepts I am thinking about at the moment. I currently work for Microsoft in the St. Paul office of the Expression product group.

RecentPosts