Tuesday, November 10, 2009

Dynamic duck typing in .Net 3.5

I just saw a post about wrapping reflection as extension methods.

Reflection as such is not rocket science. Reflection is for discovering features of objects you don't know how is structured at compile time or it is for interaction with objects you know how operate but don't have a type for.
It's not a big problem to use reflection to access regular properties or methods. The extension methodsI created for wrapping properties and non generic methods are merely wrapping some simple reflection calls.

Alright, let's get to it:

Setting the value of a property.
o.SetValue<string>("Title","Some title");

Getting the value of a property.
string title = o.GetValue<string>("Title");

Calling a method

With generic methods its a different story. I can't find it just by a name. I have to find the version that supports generics. Not only do I need to provide parameters for the method call but also the generic types. This means I can't wrap a generic method call in just one extension method.

This is the situation I want to handle. I have an object and want to find a Dao object for it to be able to save it. If you know the type compile it could be something like this:

IDao dao = factory.GetDao<Blog>();

The same code executed with my new extension methods:

object o;// object you want to save
object dao = factory.GetMethod<object>("GetDao",o.GetType()).Call();

It's a bit more verbose than direct code, but a lot more compact and precise than if you had to use the System.Reflection namespace. The GetMethod method gathers the name of the method together with a list of types that defines the methods generic properties. The Call method accepts the parameters for the method call and invokes the method.

The source for the extension methods can be found here.

No comments:

Post a Comment