views:

61

answers:

2

I have a number of data access methods that accept a dynamic object parameter (i.e., dynamic foo). I can't use an interface to define to type the input parameter due to existing code. I am setting properties in the data access methods, but using dynamic without checking to see if the properties/methods exist makes me nervous.

So I am looking for a way to check the runtime properties/methods of a dynamic object, but I would rather not use reflection due to the perf impact. Is there another/recommended way to query the properties/methods of a dynamic object?

Thanks, Erick

+2  A: 

I would look at this problem a bit differently. If you're using the objects with dynamic then whether or not the properties are accessible via reflection is irrelevant. It only matters if they are accessible via dynamic. So why not just use the properties and catch the execption that would result from their abscence?

JaredPar
+1 from me - this would be my approach. Just use the object, and handle the exceptions as/if they come.
Reed Copsey
@Reed, congrats on 100K!
JaredPar
@JaredPar: Thanks! Just passed it this morning :D
Reed Copsey
Jared, I think you are right. I always try to avoid exceptions, but this might be a good case to use one, as the absense of a property or method really should be an exceptional case.
Erick T
+2  A: 

Reflection doesn't actually work (the way you'd expect) on dynamic types. You need to check for IDynamicMetaObjectProvider, then use its methods to determine whether a member is available on the type.

The problem is that it's perfectly acceptable for a dynamic type to add new members at runtime. For an example, see ExpandoObject. It only adds new members on set operations, but you can, just as easily, make a dynamic type that always returns a valid member, no matter what is passed into it, ie:

dynamic myType = new DynamicFoo();
Console.WriteLine(myType.Foo);
Console.WriteLine(myType.Bar);
Console.WriteLine(myType.Baz);

This can be done by overriding the get accessor, and just making them always valid. In this case, reflection would have no way to tell what would work here...

Reed Copsey
Reed, this is the answer that I needed but I decided to take the approach of trying it and letting the exception get thrown. Thanks!
Erick T