Core PlatformComplete guide

Source Generators

C# source generators are compiler components that inspect source, symbols, additional files, and analyzer configuration, then add strongly typed C# to the same compilation. They move repeatable discovery and glue code from runtime or developer maintenance into a deterministic build step.

Overview

A production generator is a small compiler extension, not a text-templating shortcut. It runs inside the compiler and IDE, where latency, determinism, compatibility, diagnostics, and failure isolation directly affect every consumer. Modern generators implement IIncrementalGenerator and describe a graph of immutable transformations. Roslyn can cache unchanged values when the pipeline filters early, projects symbols into stable value models, and combines only inputs that actually affect an output. Generation is additive: it can contribute syntax trees but cannot rewrite user code. Good uses include serializers, strongly typed configuration, registration maps, protocol clients, and repetitive partial-type members whose complete inputs are available at compilation. Poor uses include business logic, network-dependent generation, arbitrary file mutation, or tasks better expressed by a normal library, analyzer, code fix, or MSBuild target. A shippable generator also needs intentional packaging, compiler-version compatibility, readable output, stable hint names, actionable diagnostics, snapshot and compilation tests, performance measurements, and a documented escape hatch when generation is unsuitable.

What you will learn

  • Explain the compilation lifecycle and distinguish generators from analyzers, code fixes, reflection, templates, and MSBuild tasks.
  • Design an incremental pipeline that filters syntax cheaply and converts Roslyn symbols into stable immutable value models.
  • Generate readable, deterministic, collision-safe source without rewriting user syntax or depending on mutable global state.
  • Report precise diagnostics for invalid consumer declarations and preserve useful locations in compiler output.
  • Package and consume a generator as an analyzer while keeping compiler dependencies private and compatible.
  • Test generated text, output compilation, diagnostics, determinism, runtime behavior, and incremental performance.

Prerequisites

  • Strong C# knowledge including attributes, partial types, symbols, nullable reference types, records, and project references.
  • Familiarity with the .NET build pipeline, NuGet packaging, MSBuild items and properties, and compiler diagnostics.
  • Basic understanding of syntax trees versus semantic symbols and why IDE-time work must remain fast and cancellation-aware.

When to use Source Generators

Good fit

  • A repeatable strongly typed API can be derived completely from declarations, attributes, AdditionalFiles, or compiler-visible build configuration.
  • Runtime reflection, dynamic activation, or handwritten registration creates measurable startup, trimming, AOT, or maintenance costs.
  • A library must produce compile-time errors and discoverable generated APIs while keeping consumer code concise.

Choose another approach when

  • Inputs require a database, network request, machine-specific state, current time, or writes outside compiler-provided outputs.
  • A normal generic library, source-generated framework feature, IDE template, analyzer/code fix, or explicit handwritten code is simpler.
  • Generated behavior would hide important domain decisions or create an API larger and harder to understand than the repetition it removes.

Key concepts

Compiler integration

A generator receives compiler-controlled inputs and contributes syntax trees before emit; it is loaded like an analyzer and does not execute in the application.

Incremental graph

IIncrementalGenerator registers providers and transformations whose values Roslyn can cache and recompute selectively.

Syntax filtering

A cheap predicate eliminates most nodes before semantic work; attribute-driven discovery should normally use ForAttributeWithMetadataName.

Semantic symbols

Symbols provide resolved types, accessibility, namespaces, attributes, and members; syntax alone cannot reliably answer those questions.

Stable value models

Pipeline stages should project Roslyn objects into small equatable records containing only values that influence generation.

Source emission

RegisterSourceOutput turns validated models into deterministic UTF-8 C# with unique stable hint names and nullable-aware declarations.

Diagnostics

ReportDiagnostic gives consumers actionable IDs, severity, messages, and source locations instead of exceptions or silently missing output.

Additional inputs

AdditionalFiles and AnalyzerConfigOptions support controlled non-C# inputs and compiler-visible MSBuild configuration without arbitrary environment access.

Packaging contract

Generator assemblies belong under analyzers/dotnet/cs in a package; Roslyn dependencies usually remain private and consumer runtime assets stay separate.

Compatibility boundary

A generator runs in the host compiler, so target framework, Roslyn API version, language features in emitted code, and consumer SDK support must be tested deliberately.

Architecture

The compiler turns user declarations and controlled build inputs into a cacheable incremental graph. Validated value models produce diagnostics and generated C# that joins user code in the final compilation.

Source + AdditionalFiles
Cheap candidate filter
Semantic value model
Validation + diagnostics
Deterministic source
Output compilation

Conceptual architecture · Adapt to your system context

Implementation walkthrough

Start from the consumer contract and the smallest complete set of compile-time inputs. The generator should behave like a pure function from stable values to source and diagnostics.

  1. 01
    Define the generated API

    Write representative consumer code and generated output first. Decide naming, accessibility, partial-type requirements, nullable behavior, generic constraints, conflicts, and opt-in semantics.

  2. 02
    Create the Roslyn component

    Use a dedicated analyzer project, target a compiler-compatible framework such as netstandard2.0 when broad tooling support matters, reference Microsoft.CodeAnalysis privately, and enable analyzer rules.

  3. 03
    Discover candidates narrowly

    Prefer ForAttributeWithMetadataName for attributed targets. Keep the syntax predicate allocation-light and defer symbol inspection to the transform callback.

  4. 04
    Project stable models

    Extract namespace, type shape, members, configuration, and locations into immutable equatable data. Do not carry Compilation, ISymbol, or SyntaxNode farther than needed.

  5. 05
    Validate and diagnose

    Detect non-partial targets, duplicate names, unsupported nesting or generic shapes, inaccessible members, and configuration errors; report stable documented diagnostic IDs at useful locations.

  6. 06
    Render deterministic source

    Order collections ordinally, escape identifiers and literals, use fully qualified framework types where appropriate, emit nullable context, and derive unique hint names from full identities.

  7. 07
    Package, consume, and test

    Reference the project as an Analyzer with ReferenceOutputAssembly=false, package the DLL under analyzers/dotnet/cs, inspect emitted files, and run snapshot, diagnostic, compilation, runtime, and performance tests.

Code example

The dedicated sample injects its marker attribute, discovers attributed types through the semantic-aware incremental API, and emits one output per stable target model.

TelemetryGenerator.cs
[Generator(LanguageNames.CSharp)]
public sealed class TelemetryGenerator : IIncrementalGenerator
{
    public void Initialize(IncrementalGeneratorInitializationContext context)
    {
        context.RegisterPostInitializationOutput(static output =>
            output.AddSource("GenerateTelemetryAttribute.g.cs", AttributeSource));

        var targets = context.SyntaxProvider.ForAttributeWithMetadataName(
            "Telemetry.Generated.GenerateTelemetryAttribute",
            static (node, _) => node is TypeDeclarationSyntax,
            static (syntaxContext, cancellationToken) =>
                CreateTarget(syntaxContext, cancellationToken));

        context.RegisterSourceOutput(targets, static (output, target) =>
        {
            if (!target.IsPartial)
            {
                output.ReportDiagnostic(Diagnostic.Create(
                    TypeMustBePartial, target.Location, target.FullyQualifiedName));
                return;
            }

            output.AddSource(target.HintName, Render(target));
        });
    }
}

Testing strategy

A generator test suite must verify both sides of the compiler boundary: the source and diagnostics it produces, and the consumer compilation and behavior that result.

  • Run CSharpGeneratorDriver against minimal in-memory compilations and assert every expected diagnostic ID, severity, message argument, and location.
  • Snapshot or compare normalized generated files so API, formatting, ordering, hint names, and nullable changes are intentional reviews.
  • Inspect the updated output compilation for errors and test representative consumer calls against the generated API.
  • Run the same input repeatedly and reorder irrelevant declarations to prove deterministic output and avoid unstable build artifacts.
  • Use incremental step tracking or benchmarks on large representative projects to detect broad invalidation, excessive allocations, and IDE latency regressions.

Security considerations

Generators execute during builds and design-time compilation, often on developer machines and CI agents. Treat them as supply-chain code with access that must be minimized.

  • Never fetch network content, read secrets, inspect arbitrary machine directories, or execute tools from a generator; use declared AdditionalFiles and compiler-visible configuration only.
  • Pin, review, scan, and sign generator packages like build infrastructure because a compromised generator runs wherever consumers compile.
  • Do not embed credentials, absolute paths, environment values, or sensitive AdditionalFiles into generated source, diagnostics, or build logs.
  • Escape identifiers, strings, namespaces, and file-derived values before emission so untrusted inputs cannot create unintended declarations or directives.
  • Keep generated APIs least-privileged and do not bypass authorization, validation, or serialization policy simply because code is produced at compile time.

Performance and scalability

Generator latency is multiplied across builds and keystrokes. Incremental APIs help only when the pipeline exposes narrow, comparable values instead of invalidating the whole graph.

  • Filter syntax with the cheapest possible predicate and prefer ForAttributeWithMetadataName over scanning every declaration and manually resolving attributes.
  • Project symbols into small equatable models before combining streams; retaining Compilation or large syntax objects defeats useful caching.
  • Avoid Collect unless an output truly depends on the complete set, and emit per-item sources so one changed type does not regenerate unrelated files.
  • Honor cancellation tokens and keep transforms pure, synchronous, and free of locks, mutable static caches, file I/O, and network I/O.
  • Measure clean build, warm build, single-file edit, allocation, and generated-source size on realistic solutions rather than assuming incremental means fast.

Deployment and operations

A generator is deployed through project references or analyzer assets in NuGet, and its host is the consumer's compiler rather than the consumer application runtime.

  • Package generator assemblies under analyzers/dotnet/cs and verify the nupkg contents; do not place the generator in lib as a normal runtime dependency.
  • Keep Microsoft.CodeAnalysis references PrivateAssets=all and test against the oldest and newest supported SDK or Visual Studio compiler hosts.
  • Separate runtime attributes or helper abstractions into a contracts assembly when generated code must reference public runtime types.
  • Build a sample consumer from the packed package in CI, with warnings as errors, deterministic build checks, and compiler-generated-file inspection.
  • Version generated public APIs and diagnostic behavior semantically, document breaking changes, and provide migration guidance or opt-outs.

Common problems and fixes

Likely cause: The project was referenced as a normal assembly or the package placed the DLL outside analyzer assets.

Fix: Use OutputItemType=Analyzer and ReferenceOutputAssembly=false for project references; inspect the nupkg for analyzers/dotnet/cs.

Likely cause: Candidate filtering, metadata attribute name, namespace, partial declaration, or semantic validation excluded the target.

Fix: Inspect generated files and generator diagnostics, reduce to one consumer declaration, and test the discovery pipeline with GeneratorDriver.

Likely cause: The generator targets an incompatible runtime or references a Roslyn API/dependency unavailable in the host compiler.

Fix: Target a supported framework, minimize dependencies, keep Roslyn assets private, and test the published package against supported compiler hosts.

Likely cause: The pipeline carries Compilation or symbols too far, calls Collect broadly, or combines unrelated global inputs.

Fix: Project early to equatable values, split independent streams, emit per target, and inspect incremental step reasons in tests.

Likely cause: Hint names are based only on simple type names or member iteration depends on nondeterministic order.

Fix: Derive hint names from full identities, sanitize consistently, order inputs ordinally, and add repeatability tests.

Likely cause: The IDE and CLI use different SDK/compiler versions, configuration, AdditionalFiles, or analyzer assets.

Fix: Pin the SDK with global.json, compare binlogs and generated files, and reproduce with the packed generator in a clean consumer.

Best practices

  • Start with the generated consumer API and keep generation opt-in, predictable, and easy to inspect.
  • Prefer IIncrementalGenerator and ForAttributeWithMetadataName for modern attribute-driven generators.
  • Convert Roslyn symbols into minimal stable models before expensive combination or collection steps.
  • Generate one deterministic file per target with fully qualified framework types and collision-safe hint names.
  • Report actionable diagnostics for consumer mistakes and track rule releases as part of the public contract.
  • Package and test the actual analyzer asset rather than proving only a directly referenced generator project.
  • Benchmark IDE-like incremental edits as well as clean builds and treat latency regressions as product defects.
  • Keep business policy in normal source code; generation should remove mechanical repetition without hiding important decisions.

Production checklist

  • The use case is fully determined by compile-time inputs and is simpler than the runtime or handwritten alternative.
  • Candidate discovery is narrow, semantic analysis is delayed, and pipeline values are immutable and equatable.
  • Generated C# is readable, nullable-aware, escaped, deterministically ordered, and uses collision-safe hint names.
  • Invalid input produces documented diagnostics with stable IDs and precise locations; expected mistakes do not throw exceptions.
  • Tests cover source snapshots, diagnostics, output compilation, runtime consumption, determinism, and incremental performance.
  • The package contains correct analyzer assets, private Roslyn dependencies, release tracking, and a clean sample consumer build.
  • Supported SDK, compiler, language, and target-framework ranges are explicit and exercised in CI.
  • The generator performs no undeclared file, network, secret, process, clock, or machine-dependent work.

Common interview questions

When does a source generator run?

It runs inside compiler and IDE compilation processes and adds syntax trees before emit. Its code does not become an application runtime component unless generated source explicitly references a separate runtime library.

Why prefer IIncrementalGenerator?

It expresses generation as composable providers and transformations that Roslyn can cache. The benefit depends on using narrow stable values; carrying the whole compilation through the graph can still invalidate everything.

Can a generator modify existing source?

No. Generation is additive. An analyzer can report a problem and a code fix can offer an edit, but a generator cannot replace or mutate a user's syntax tree.

Syntax node or symbol: which should a generator use?

Use syntax for cheap candidate filtering and symbols for resolved meaning such as types, accessibility, attributes, and members. Efficient generators deliberately use both at different stages.

How do generators differ from reflection?

A generator discovers known compile-time structure and emits ordinary typed code, improving diagnostics and often trimming or AOT behavior. Reflection discovers runtime metadata and handles shapes unavailable at compilation but adds runtime cost and dynamism.

How should invalid consumer input be handled?

Emit stable diagnostics with documented IDs, severity, useful arguments, and precise source locations. Expected invalid code should not crash the generator or silently omit output.

What makes an incremental generator actually incremental?

Early filtering, small equatable models, narrow combinations, per-item output, deterministic transforms, and avoiding broad compilation or Collect dependencies allow Roslyn to reuse unaffected pipeline values.

Dedicated GitHub sample

Clone, run, test, and modify the focused implementation created for this guide.

Verified sample

Source Generators Telemetry

A focused .NET 10 sample demonstrating IIncrementalGenerator, attribute-based discovery, semantic symbol projection, deterministic source emission, compiler diagnostics, analyzer consumption, generated-file inspection, and generator-driver tests.

.NET 10C# 14Roslyn 5.0xUnit
dedicated-sampleincremental-generatorcompiler-diagnosticsdeterministic-outputtesting
Run
dotnet run --project src/TelemetryDemo
Test
dotnet test SourceGeneratorsTelemetry.slnx