Thinking about Performance
I know what you're thinking: Building types dynamically is interesting, but it must be an absolute pig, performance-wise. You're right. Sort of. Reflection has a reputation for poor performance that's well-deserved in certain areas. But remember that dynamically creating a new type is a one-time cost. Once the type is built, it's compiled into an assembly just like any other type in .NET.
The process of copying prototype objects, however, incurs an ongoing performance penalty. Table1 shows the three different methods of instantiating dynamic types and, just for comparison, I also timed the creation of the baseclass using the new operator. Not surprisingly, using the new operator is the fastest. But instantiating dynamic types using reflection wasn't too far behind. The prototype pattern ended up way behind the reflection-based approach, as deserialization proved to be the bottleneck.
Table 1. Hydration is the pig. When creating new instances of dynamic types, serialization ends up being the biggest performance penalty.
||Objects created/second *
*My desktop has PentiumIV, and 1GB of RAM.
You should still consider these numbers with some perspective. In absolute terms, creating 18,000 objects per second isn't too badeven if it is two orders of magnitude slower than using the new operator. And there are ways to mitigate even these costs. Depending on the specifics of your application, you could build a factory class that copies prototypes on a low-priority worker thread, building up a cache of objects for when they're needed.
Moderation in All Things
This is not idiomatic C#, not yet anyway. But the platform is still young, and the ability to dynamically create new types is one thing setting .NET apart from Java. After all, it took the C++ community years to discover the true power of templates. Maybe, over the next few years, we'll all be taking advantage of the dynamic typing power of the .NET framework.