DuckCallLib v0.2, Introducing object.As<T>
Scratching another itch, and after reading some feedback from mihailik on my previous post - I decided to implement some additional functionality in DuckCallLib to make it more useful. As before, the bits are available on codeplex.
So, again, with great fanfare, I introduce my first cut at an dynamic proxy mechanism that works generally for objects that leverages the duck typing mechanism we previously built. The purpose of this is to allow a consumer of an object to recognize when an object they don't control has certain behavior, and without having to implement a wrapper on your own, simply apply an interface to the object at runtime, whether it explicitly supports the interface or not.
Usage is generally as follows:
interface IEggable { string LayEgg(); }
class Platypus { public string LayEgg { return "egg"; } } //notice it does not implement IEggable
//we don't know for sure if a platypus can lay eggs, since we are dealing with it as an object, but we can try
object someObjectThatMightLayEggs = new Platypus();
var eggLayingPlatypus = someObjectThatMightLayEggs.As<IEggable>();
Assert.IsTrue(eggLayingPlatypus.LayEgg() == "egg");
Still a work in progress. I doubt I handle generics well, and I need to something other than crash on method missing, but the hardest part (for me) - generating the dynamic proxy that implements the interface dynamically using Reflection.Emit (ugh) is done.
Enjoy, and as always, feedback is appreciated.
Update, duh moment, I just realized I started to re-implement this (Jason Bock) and this (Castle Project). Ah well, if nothing else, going through creating one of these has given me a much better sense for how to do nifty stuff with Reflection.Emit.