Take the 2-minute tour ×

Does anyone know of a library which helps with generating C# code? For example, if I need to generate a *.cs file containing the definition of a class, I'd like to be able to specify the class and method bodies using an object tree (similar to expression trees) and then tell the library to give me well the formatted C# code as a string.


share|improve this question
To clarify, I want to call the library from custom C# code. –  jthg Jan 26 '11 at 17:08
add comment

3 Answers

up vote 4 down vote accepted

Have you looked at Microsoft.CSharp.CSharpCodeProvider?

Provides access to instances of the C# code generator and code compiler.

share|improve this answer
It sure is, it's part of System.dll. –  Sasha Goldshtein Jan 26 '11 at 16:45
+1 and I would like that with CodeDom you can target different languages with same codebase. –  Felice Pollano Jan 26 '11 at 16:45
@Sasha - should have looked at what assembly it was in... thanks :) –  Oded Jan 26 '11 at 16:46
I never realized that that provider goes both ways. I'll take a look at what it does. –  jthg Jan 26 '11 at 17:04
add comment

There are many tools for code generation and they are listed below:

Code Smith codesmithtools dot com

codegeneratorpro dot com


Code generators may sound like saving a lot of time, in reality it depends on the kind of project your working on.

Look into System.CodeDom and CSharpCodeProvider.

share|improve this answer
add comment

I'm rather fond of Terance Parr's StringTemplate. It's at the core of the compiler building tool ANTLR — StringTemplate is responsible for for code generation, allowing ANTLR to target just about any language for its compilers.

You can download the latest C#/.Net port from http://www.stringtemplate.org/download.html

You can read about string template in these papers by Dr. Parr:

CodeProject has an article on code generation with StringTemplate as well: http://www.codeproject.com/KB/codegen/DotNetCodeGeneration.aspx

share|improve this answer
add comment

Your Answer


