Lots of first chance Microsoft.CSharp.RuntimeBinderExceptions thrown when dealing with dynamics

Whenever a property on a dynamic object is resolved, the runtime tries to find a property that is defined at compile time. From DynamicObject doco:

You can also add your own members to
classes derived from the DynamicObject
class. If your class defines
properties and also overrides the
TrySetMember method, the dynamic
language runtime (DLR) first uses the
language binder to look for a static
definition of a property in the class.
If there is no such property, the DLR
calls the TrySetMember method.

RuntimeBinderException is thrown whenever the runtime cannot find a statically defined property(i.e. what would be a compiler error in 100% statically typed world). From MSDN article

…RuntimeBinderException represents a
failure to bind in the sense of a
usual compiler error…

It is interesting that if you use ExpandoObject, you only get one exception when trying to use the property:

dynamic bucket = new ExpandoObject();
bucket.SomeValue = 45;
int value = bucket.SomeValue; //<-- Exception here

Perhaps ExpandoObject could be an alternative? If it’s not suitable you’ll need to look into implementing IDynamicMetaObjectProvider, which is how ExpandoObject does dynamic dispatch. However, it is not very well documented and MSDN refers you to the DLR CodePlex for more info.

Leave a Comment