Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Code generation using .net

are there any classes in the .net framework that allow me to generate classes that i can save as .cs or .vb files ?

like image 324
Hannoun Yassir Avatar asked Jan 09 '10 22:01

Hannoun Yassir


People also ask

What is code generator C#?

C# Source Generators is a Roslyn compiler feature introduced in C#9/. NET 5. It lets C# developers inspect user code and generate new C# source files that can be added to a compilation.

What is a code generation tool?

A code generator is a tool or resource that generates a particular sort of code or computer programming language.

What is source code Generation?

Source-code generation is the process of generating source code based on a description of the problem or an ontological model such as a template and is accomplished with a programming tool such as a template processor or an integrated development environment (IDE).


2 Answers

Do you really need specific .NET classes, or can you live with an addin to Visual Studio??

If you have Visual Studio, definitely check out the T4 template - one of the least known and yet most valuable assets in VS!

  • T4 (Text Template Transformation Toolkit) Code Generation - Best Kept Visual Studio Secret
  • Visual Studio's T4 Code Generation
  • T4 Architecture and anything else on Oleg's excellent blog/website on T4
  • T4: Text Template Transformation Toolkit

There's at least a command-line tool that you could call from .NET code to do the transformation, but I'm pretty sure you could also invoke some transformation engine as a .NET class and have it generate C# or VB.NET code from your T4 template programmatically.

Typically, using T4 is a lot easier than CodeDom - it has its limits, but for the most part, it's a great technology to get things done fast and easy.

like image 86
marc_s Avatar answered Sep 27 '22 22:09

marc_s


See the System.CodeDom namespace. Basically you use CodeDom to create an abstract model of the class. Then you instantiate a CSharpCodeProvider or VBCodeProvider and use one of the CodeDomProvider.GenerateCodeFrom... methods to emit it as the appropriate kind of source code. This is the underlying technology used by the Windows Forms Designer, xsd.exe, etc.

Be warned, however, that CodeDom is quite verbose and fiddly to work with. If your classes a moderately complex, you may want to use a templating engine such as T4 or NVelocity instead.

like image 41
itowlson Avatar answered Sep 27 '22 22:09

itowlson