Using the LateBinder

By on 12/11/2008

Heh, I seemed to have not realized that I didn't include any usage information on the LateBinder in the last post.  So here is the how and why you'd want to use this class.

Say you have a need to dynamically get or set the property of some class using the string name of the property.  Normally, the answer would be to use reflection, get the PropertyInfo, extract the MethodInfo of the getter or setter, and then invoke that method using the reflection API.  Hardly very usable ... and if you're not careful, you will end up paying the reflection cost everytime because you have to keep looking up the PropertyInfo and all that.

Enter the LateBinder<T> ... using this class, you can do:

MyClass mcInstance = new MyClass();

LateBinder<MyClass> binder = LateBinder<MyClass>.Instance;
binder[mcInstance, "Name"] = "my name";
string name = (string)binder[mcInstance, "Name"];

The late binder (on windows) uses the System.Reflection.Emit API to generate a DynamicMethod, which is much faster to call than the reflection invoke because it's pre-compiled using custom built IL instructions.  It also caches them in the late binder instance so that it only has to be compiled once ... and furthermore, if you use the singleton .Instance method, you only have to do the compilation once per application run since it keeps the data around in a static variable.

Beneath the hood, the original version of the late binder was using this class.  But I had to change the design of the class to support the cross platform aspect of it and to add in the static support.  It was pretty fun, I ended up using reflector to decompile some sample code I wrote in a console app so I could see what IL instructions I had to use to get/set the statics ... so with this version of LateBinder, it supports getting and setting both properties and fields ... regardless of whether they are instance or static fields/properties.

Now, on XBox and Zune, the story changes a bit because System.Reflection.Emit does not exist.  So, in this new version I posted, it falls back to simply using reflection.  However, it does keep the propertyinfo in that static cache, so at least you won't have to pay the penalty of looking for it every time.

So to get back to the original question on usage (ie. when/why would I want to use it) ... it probably wouldn't be a good idea to use this in a tight loop in runtime code.  However, for certain tools and custom serialization code ... it could certainly be very useful.  For example, you can relatively easily write code using this that will transfer property values from one class to another ... assuming the property names are the same.  The list goes on and on as to how this is useful.

See more in the archives