A source generator is a compiler extension that inspects code during compilation and emits additional C# files included in that compilation. It can reduce boilerplate and move work from runtime to compile time, often improving performance compared with runtime reflection. section 14.6
Common .NET applications include source generators for:
- Regular expressions, where generated code can make Regex instances functionally identical but likely faster. section 14.6
- Logging, where generated methods define event metadata, substitute parameters, add analyzers, and help prevent avoidable allocations. section 26.2
- Razor compilation, which uses source generators to compile .cshtml files. section 14.6
Generate a regular expression
Declare a partial method with GeneratedRegex, then call it instead of constructing the expression through Regex.Replace directly. The generated method keeps the matching pattern in compiled code while preserving the application’s behavior.
Generate a logging method
A partial method decorated with LoggerMessage can define the event ID, log level, and message template. Calling LogLoadedRecipes(Recipes.Count) writes the structured message without constructing it through the ordinary logging call. section 26.2
