Microsoft Releases C# Source Generators

A Source Generator is a bit of code that runs during compilation and examines the program to produce additional files that are compiled together with the rest of the code.

Microsoft announced the first preview of Source Generators, which is a new C# compiler feature that enables C# programmers inspect user code and generate new C# source files that can be added to a compilation.
 
It allows developers do two important things:
  • Source Generators enables retrieve a Compilation object that represents all user code that is being compiled. Then, this object can be inspected and developers can write code that works with the syntax and semantic models for the code being compiled, similar to analyzers today.
  • Secondly, it generates C# source files that can be added to a Compilation object during the course of compilation. So basically, now developers can provide additional source code as input to a compilation while the code is being compiled.
When combined, the above two things make Source Generators very useful. Source Generators enables developers to inspect user code with all of the rich metadata that the compiler builds up during compilation and then issue C# code back into the same compilation that is based on the data they have analyzed.
 
The below image shows Source generators run as a phase of compilation.
Source: Microsoft 
 
Well, a Source Generator is a .NET Standard 2.0 assembly. It is loaded by the compiler along with any analyzers and is usable in environments where .NET Standard components can be loaded and run.
 
To learn more you can visit the official announcement here.