Building .NET code generators
.NET 5 is finally live and there are a number of amazing new things that came out with it. You can read the announcement post here: https://devblogs.microsoft.com/dotnet/announcing-net-5-0/
But one of the things that I've been waiting for a very long time and was most excited by was the GA release of code generators! I've been waiting for something like this for years, and was super excited about the early announcements and releases, but didn't really get a chance to play with them much. Plus, the early releases were a bit tricky to use, and the tooling was very much lacking, so I didn't apply them in any projects until now
The general principle is simple - the code generators are somewhat similar to analyzers in behavior, they will run as part of the code analysis / build, but the main difference is that you get the ability to add new source files to your compilation on the fly. There are some caveats though, some of them being:
- The process is additive only - you can't modify or delete existing code using code generators (at least for the moment), you can only add new code
- All code generators will run in parallel with each other, and can't inspect each other's generated output. This means you can't have code generators analyze code that was created by a different generator
This may change in the future, as source generators evolve and improve.
So let's see what it takes to generate some code!