What are Source Generators
For repetitive boilerplate we all want to get the code generated in some way. Previously we used Build tasks with custom code and T4 templates (*.tt).
Since .Net 5 there is a new way: Source Generators. It’s a step within compilation pipeline, that can inspect compiled code and add extra code to your project that is then optimized and converted to IL as part of the project. This gives reflection-like power with regular code performance.
I will demonstrate a feature on a small project: FastMapper. Normally we use AutoMapper to map objects, but it relies on reflection and therefore has performance penalty in runtime. I know that other mapping libraries that use Source Generators already exist, I just want to show the concept.
Prerequisites
- Visual Studio 2022 or higher
- In VS, .Net Compiler Platform SDK
Start
- Create .Net project where we want to test the thing.
I will continue writing it. I promise. But if you are curious, write a comment, it will help me prioritize.