I was reading this post by Ted Neward and it got me thinking. While I agree that being able to parse code would be really useful (all issues with that aside) there is something that I would like to see before that which is a higher level abstraction over the top of CodeDom.

As an example, lets say we wanted to define an exception using CodeDom. Today we would have to whip up a CodeCompileUnit, build a CodeNamespace, add a CodeTypeDeclaration and populate it. If we wanted to support serialization or any custom properties we would need to go ever further.

Rather than having to do this it would be cool to be able to use higher level abstractions. To quickly demonstrate the idea I created this lump of sample code.

CodeExceptionUsage

Basically its just a CodeException class which is specifically designed for emitting an exception. You just assign the CodeNamespace to its Namespace property and when you generate the CodeCompileUnit that its nested in it slurps in the exception code. When this code is run it will emit the code to the console.

CodeExceptionOutput

Now – building an exception is pretty trivial, even with the current CodeDom, but imagine what you could do if you dug through all the patterns material out there and build CodeDom abstractions for them? The implementation would be fairly important.

You wouldn’t want to just embed an abstraction into a CodeCompileUnit since an abstraction could easily span assemblies, thats why I took the approach of wiring up to the PopulateTypes event on the CodeNamespace. That way if you had an abstraction that represented a pattern you could just hand it the CodeObject that it needed to emit against and the code would just end up in the right location.

CodeExceptionImplementation

Food for thought.