What is a source generator in C#?
Quick Answer
A source generator is a Roslyn component that runs during compilation, inspects your code, and adds new source files to it. It replaces run-time reflection or IL emit with code produced at build time — used by System.Text.Json, LoggerMessage, [GeneratedRegex], and for boilerplate like INotifyPropertyChanged.
A source generator plugs into the compiler and generates extra C# files while your project builds, based on looking at your existing code and attributes. The point is to replace things that used to happen via reflection at run time with code that's written at compile time — so System.Text.Json's source generator produces a fast, hard-coded serializer instead of reflecting over your type on the first call, and [LoggerMessage] generates zero-allocation logging methods. It's also what makes trimming and Native AOT viable, because the generator sees all the code the linker would otherwise strip.
- Benefits: no reflection cost at run time, trimming/Native-AOT friendly (the tool can see all the code), errors surface at build time.
- Examples:
JsonSerializerContextgenerates fast serializers;[LoggerMessage]generates allocation-free logging methods;[GeneratedRegex]compiles the regex at build time. - You can write your own (implement
IIncrementalGenerator) for domain-specific boilerplate — mappers, DTOs, DI registration.