Glossary / Source generators

Source generators

C# source generators are compiler extensions that inspect a compilation and add source code during compilation. They can remove repetitive boilerplate, create strongly typed serializers or registries, and improve trimming/AOT compatibility compared with runtime reflection, while introducing generated-code diagnostics and build complexity.

Generator model

Roslyn source generators receive compilation syntax/semantic information and emit source files; incremental generators use a tracked pipeline to cache work based on changed inputs. Generators add code but do not directly rewrite user source. They run as analyzer assemblies during compilation and can report diagnostics. Generated code is part of the same compilation and can integrate with partial types.

Generators must be deterministic, efficient, and robust to incomplete code while the IDE is editing. They should avoid depending on current working directory or machine-specific state. Generated output can be inspected through compiler settings, and tests should verify source output plus diagnostics across language versions and target frameworks.

Source generators differ from analyzers: generators emit code; analyzers report diagnostics and optional code fixes. A package can contain both. Newer compiler APIs and language features change; pin Roslyn package compatibility with supported SDKs.

Engineering guidance

Use generators when repetitive patterns are systematic and static structure is available. Keep a hand-authored escape hatch when generated abstractions become opaque. Test incremental behavior, deterministic output, diagnostics, and consumer compilation. Document how to inspect generated files and handle generator failures.

Interview questions

  1. What does a source generator do? Adds source files during compilation based on compilation input.
  2. Does it modify existing source? No; it contributes generated code.
  3. Why incremental generators? They cache pipeline computations and respond efficiently to changes.
  4. Generator vs analyzer? Generator emits source; analyzer reports code diagnostics and may offer fixes.
  5. How do generators help AOT? They can replace runtime reflection/discovery with statically visible generated code.

References