Search code examples
c#dynamiclanguage-features

Is Reflection the best way to determine the presense/absence of property/method on a dynamic object?


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 performance impact. Is there another/recommended way to query the properties/methods of a dynamic object?

Thanks, Erick


Solution

  • 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...