⚙️ C# / .NET Intermediate

What are source generators in C#?

Answer

Source generators (C# 9+) are compile-time code generation tools that run as part of the compilation process and add additional C# source files to the compilation. They analyze existing code (via Roslyn APIs) and generate new code based on it — eliminating runtime reflection and boilerplate. Examples of source generators in .NET: System.Text.Json source gen (generates fast serialization code, AOT-compatible), Regex source gen ([GeneratedRegex] — compiles regex at build time), LoggerMessage source gen (efficient structured logging), AutoMapper source gen, Dapper.AOT, MediatR.SourceGenerator. Build your own: implement IIncrementalGenerator, read syntax trees, emit C# code as strings. Benefits over reflection: (1) Zero runtime overhead. (2) Compile-time errors. (3) AOT/trimming compatible. (4) Better IDE support. Source generators have largely replaced T4 templates and some uses of reflection.