C# Reference ยท Reflection, Attributes and Metadata
C# source generators
Reference for C# source generators: IIncrementalGenerator, partial classes, built-in generators like LibraryImport and JSON, and limits for generated code.
A source generator is a component that runs inside the C# compiler (Roslyn), inspects your code and adds new source files to the compilation. The generated code is normal C#: you can read it, debug into it and it is fully type-checked. Because it exists at compile time, nothing is discovered through reflection at run time, which makes it fast and compatible with trimming and Native AOT.
The runtime ships several generators you already use: [GeneratedRegex], [LibraryImport], [LoggerMessage], and the System.Text.Json serializer contexts. You trigger them by writing a partial class or method plus an attribute, and the generator fills in the body.
[GeneratedRegex(@"\d+")] private static partial Regex Digits(); // body generated at build time
Try it
This site's runner compiles one file without generators, so the examples show what a generator produces by writing the generated half by hand.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.
How a generator is written
A generator is a separate project that targets netstandard2.0 and references Microsoft.CodeAnalysis.CSharp. Modern generators implement IIncrementalGenerator, which describes a pipeline that Roslyn caches between keystrokes so the IDE stays responsive. This code is read-only here, because the runner has no NuGet or MSBuild:
[Generator] public sealed class AutoDescribeGenerator : IIncrementalGenerator { public void Initialize(IncrementalGeneratorInitializationContext context) { var classes = context.SyntaxProvider.ForAttributeWithMetadataName( "AutoDescribeAttribute", predicate: static (node, _) => node is ClassDeclarationSyntax, transform: static (ctx, _) => (INamedTypeSymbol)ctx.TargetSymbol); context.RegisterSourceOutput(classes, static (spc, symbol) => { string source = $$""" partial class {{symbol.Name}} { public partial string Describe() => "{{symbol.Name}}"; } """; spc.AddSource($"{symbol.Name}.g.cs", source); }); } }
The consuming project references the generator as an analyzer (OutputItemType="Analyzer"). Trying [GeneratedRegex] on this site's runner fails with error CS8795: Partial method 'R.D()' must have an implementation part because it has accessibility modifiers, because no generator runs there.
Usage notes
- Generators add code; they cannot change existing code. That is why the target types must be
partial. - Use the incremental API. The older
ISourceGeneratoris deprecated; it re-runs on every change and slows the IDE. - Generated files are visible. Set
EmitCompilerGeneratedFilesto write them to disk, or browse them under Dependencies > Analyzers in Visual Studio and Rider. - No access to the file system or the network from a well-behaved generator, and output must be deterministic.
- Target
netstandard2.0. The compiler loads generators in its own host, regardless of your app's .NET version. - Reporting problems: use
Diagnosticobjects so the user sees errors in the normal error list. - Replaces reflection in hot paths: serializers, mappers, DI registration and logging. See Expression trees for the run-time alternative.
- Debugging needs
Debugger.Launch()or an analyzer test harness; keep generators small and unit-test them.