Creating source generators
Source generators were introduced with C# 9 and .NET 5. They allow a programmer to get a compilation object that represents all the code being compiled, dynamically generate additional code files, and compile those too. Source generators are like code analyzers that can add more code to the compilation process.
A great example is the System.Text.Json
source generator. The classic method for serializing JSON uses reflection at runtime to dynamically analyze an object model, but this is slow. The better method uses source generators to create source code that is then compiled to give improved performance.
You can read more about the System.Text.Json
source generator at the following link: https://devblogs.microsoft.com/dotnet/try-the-new-system-text-json-source-generator/.
Implementing the simplest source generator
We will create a source generator that programmatically creates a code file that adds a method to the Program
class...