Code Generation with LINQPad 4

Today I encountered a task at work that offered the prospect of some pretty dull development work–code that needed to be written that was almost the same in multiple cases (but not quite).  It seemed like work that could benefit from the use of T4 templates, but quickly became frustrated by the process of setting up and debugging a template.  The interleaving of angle bracket markup with code was never fun in XML, and T4 templates began to resemble that very quickly.

So after abandoning the T4 template approach, I fired up LINQPad to see if I could accomplish my goal in that.  As it turned out, writing a small C# program in LINQPad for code generation was a lot easier.  I just needed to remember two key things about string substitution in verbatim string literals.  Here they are:

  1. Curly brackets need to be escaped.  So “{” should be “{{” and “}” should be “}}”.  Not doing this will result in a FormatException.
  2. Double quotes need to be escaped.  So ” should be “”.

Beyond that, it was a matter of writing a code template inside a verbatim string literal (@”<code template goes here>”) with format items where needed ({0},{1},…).

I’ve made a code sample available as GitHub gist here.  So far, I’ve used this technique to generate nearly 20 files in a fraction of the time it would have taken to write them manually.  Very little manual tweaking of the files was needed after generation, which left more time to test the generated code in real scenarios.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.