Tuesday, November 27, 2007

Close but not quite...

I was pondering different mechanisms for adapting some existing reflection-based code to transparently perform reflection against a variety of targets: types loaded in the current AppDomain, types whose metadata has been read from disk, and types that are purely defined by an in-memory AST.  (The reason is to support running MbUnit tests inside of ReSharper.)

The xUnit.Net guys encountered this same problem.  They chose the obvious solution of defining a few new interfaces such as ITypeInfo and to write wrappers that accept .Net Type instances or ReSharper ITypeElement instances.

Sure that's a fine approach.  Can we do better?

It turns out that the .Net class library partly supports a retargetable reflection model via subclassing.  You can actually subclass Type, MemberInfo, and other types and override most of their implementation.  The Reflection.Emit library uses this feature extensively.

There's just one hitch: you can't subclass Assembly or ModuleReflection.Emit does this but you and I can't because the constructors are internal and much of the behavior is non-virtual.

Oh duck typing, where are you?