Search code examples
c#code-generationpre-build-event

c# Generate c# code before compilation/buil (Like maven plugin in java)


I have a projet in c# .net.
I need to hook the "pre build" event so I can run a c# class that will generate other c# class to the same project.
I know that in java you can generate source code using maven plugin, is it possible in .net?

Thanks.


Solution

  • There are at least two options:

    1. Use T4
    2. Add a pre-build step to the build file.

    T4 is the inbuilt way to do code generation (and widely used in ASP.NET MVC scaffolding and Entity Framework type generation). However T4 doesn't directly support compile time generation. It does either design time – with the developer triggering (re-)generation – or runtime generation; (third party tools can add compile time generation).


    Adendum (after 6 years): NuGet packages like Clarius.TransformOnBuild can also do this.

    A custom MSBuild task (including running an external program) can be used to create code which is then included in the compile. In the simplest cases the "pre-build" setting of a project can be used (the Build Events tab of the project properties). Directly working in MSBuild (and a .csproj is a MSBuild file) gives more flexibility.