1

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.

Thanks.

1
  • To clarify, I want to call the library from custom C# code.
    – jthg
    Jan 26, 2011 at 17:08

3 Answers 3

5

Have you looked at Microsoft.CSharp.CSharpCodeProvider?

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

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

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

Code Smith codesmithtools dot com

codegeneratorpro dot com

etc

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.

0

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.