Jun 01

Today I wanted to generate a bit of rather trivial C# code to provide a convenient facade to an internal library. After creating a T4 template, loading the required assembly and adding some namespace imports, I found it rather inefficient to write code in that simple text editor without IntelliSense. So of course, there is always the option to write a code generator class with a method that returns a string. The T4 template can instantiate that class, call the method and emit the value directly:

<#= new CodeGenerator().Generate() #>

Next comes the question of how to implement the generator. StringBuilder? Come on, there must be a better way. I checked in another library that I knew was using code generation. Then I saw that the library was using CodeDOM. For my simple needs, I decided that this would be sufficient for the time being (and efficient, since I didn’t want to spend too much time there).

But then I started to wonder. Will CodeDOM still work with the new .NET Core?

The answer was no.

The linked StackOverflow question already includes the “replacement” of CodeDOM (CodeDOM is referred to as some precursor to part of what Roslyn does): The “new” Roslyn compiler platform (which has been around for a while by now). More specifically, the SyntaxFactory that comes with Roslyn.

The only draw-back I see immediately: The code that uses the SyntaxFactory seems a lot more verbose than the CodeDOM API. On the plus side, the Roslyn way should be superior to CodeDOM regarding features and support for language constructs.

There are already articles available for generating code with Roslyn, so I will leave the details to the interested reader.

Leave a Reply

blog