Source Generators allow you to inspect code during compilation and generate new C# files on the fly. Unlike Reflection (runtime slow) or IL Weaving (complex), Source Generators are fast, debuggable, and integrated into Roslyn.
How it Works
flowchart LR
Source[User Code] --> Compiler[C# Compiler]
Compiler -->|Analyze| Generator[Source Generator]
Generator -->|Emit .cs| NewCode[Generated Code]
NewCode --> Compiler
Compiler --> Output[DLL/EXE]
style Generator fill:#E1F5FE,stroke:#0277BD
Example: INotifyPropertyChanged
Automate the boilerplate of MVVM.
[Generator]
public class NotifyGenerator : ISourceGenerator
{
public void Execute(GeneratorExecutionContext context)
{
// Find classes with [AutoNotify] attribute
// Generate partial class with boilerplace code
}
public void Initialize(GeneratorInitializationContext context) {}
}
Key Takeaways
- Generators can **add** code, but cannot **modify** existing code.
- Use `partial` methods and classes to create hook points.
- Expect massive performance improvements for serializers (System.Text.Json) and mappers.
Discover more from C4: Container, Code, Cloud & Context
Subscribe to get the latest posts sent to your email.