What are source generators and how do they work?
Can you imagine code that writes code for you? With new features started in C# 9, such code is possible. Let’s dive into source generators, which can do exactly what the name says: generate source code.
Source generators are part of the .NET Compiler Platform (Roslyn) SDK, which makes them available everywhere dotnet code can be developed, no matter what IDE you use. The generators read code that you write and can generate some additional code that will be added to the compilation and emitted in the resulting .dll
.
First, let me say what source generators can’t do. They can’t modify existing code. It is in the design of source generators to be able to add additional files to the compilation, but they can’t modify or remove existing files. Whether this is good or bad is a long-running discussion.
What source generators can do is they can read a compilation object representing all code that is being...