skip to content

Source Generators

An incremental source generator adds C# at compile time, usually filling partial members marked by an attribute. Interviewers ask generators vs reflection for speed and AOT.

on this pageshow

explore

questions

6

In C#, what does a source generator do during compilation, and why must the type it extends be declared partial?

level: middleimportance: must knowfreq 55%

answer

  1. build time, not run time
  2. adds files, never edits them
  3. merged type declarations
  4. missing modifier error on your half

basics

~20 s

A source generator is a compiler plug-in that inspects your code during the build and adds new C# files to the compilation. It can only add, so it extends a type by emitting another partial declaration of it.

solid answer

~40 s

A source generator is an assembly the C# compiler loads like an analyzer. During the build it reads the syntax trees and semantic model and adds new source files with `AddSource`; they are compiled with yours into ordinary IL, so nothing is discovered at run time. Generators are additive by design: they cannot edit or remove existing code. To give your type new members, a generator writes a second declaration of that type, and C# merges declarations only when every one carries `partial`; without it the build fails with CS0260. The usual contract is a marker attribute such as `[AutoDescribe]` on a `partial record struct`, plus partial members the generator fills in. Enums cannot be partial, so an enum generator adds a new static class instead.

code

csharp · 19 lines
csharp
using System.Globalization;
using Demo;

CultureInfo.CurrentCulture = CultureInfo.InvariantCulture;
var p = new Price("EUR", 12.5m);
Console.WriteLine(p.Describe());
Console.WriteLine(Status.Shipped.ToFastString());

namespace Demo
{
    [AutoDescribe]
    public partial record struct Price(string Currency, decimal Amount)
    {
        public partial string Describe();
    }

    [FastNames]
    public enum Status { Pending, Shipped, Delivered }
}

go deeper

for a junior

Recall that a generator adds C# files while the project compiles and that you mark your type partial so its half can join yours.

for a middle

Explain the additive-only rule, why the compiler needs every declaration to say partial, and what errors appear when one does not, CS0260 and CS0111.

for a senior

Show you can design the seam: marker attribute, partial type, bodiless partial members, and a fallback type for declarations that cannot be partial, such as enums.

for a principal

Frame generators as moving work from start-up into the build and the IDE, and weigh that against build time and the contract you impose on every user's type.

## What a source generator is A **source generator** is a component the C# compiler (Roslyn) loads from an assembly, the same way it loads an analyzer. While the compiler builds your project, the generator is handed a view of the compilation: the **syntax trees** of your files, the **semantic model** that knows what every name binds to, and any additional files the project passes in. From that it produces new C# text and hands it back with `AddSource(hintName, source)`. The compiler parses the new text, adds it to the same compilation, and emits one assembly from your code and the generated code together. Three consequences follow from that design: - **The output is ordinary compiled code.** Nothing is interpreted or discovered when the program runs; the generated members are IL like any member you typed. - **The work happens at build time.** The cost moves from your application's start-up into the build, and into the IDE, which runs generators as you edit or save so that IntelliSense sees generated members. - **The generator sees only what is in the compilation.** It can read your declarations and the metadata of referenced assemblies, but it never sees types that exist only at run time. ## Additive only: why the target is `partial` Roslyn's design notes for generators state the rule plainly: generators are **explicitly additive**. They may add new source to a compilation but may not modify existing user code, and they run unordered, each seeing the same input compilation and none seeing the files another generator added through the standard outputs. A generator therefore cannot open `Price.cs` and insert a method. What it can do is write a **second declaration of the same type** in a new file. C# merges several declarations of one class, struct, record, record struct or interface into a single type only when **every** declaration carries the `partial` modifier. If the generator emits `partial record struct Price { ... }` and your file says `public record struct Price(...)` without `partial`, the build fails with **CS0260** ("Missing partial modifier on declaration of type 'Price'; another partial declaration of this type exists"). If the generator tried to emit a method you already wrote, the merged type would contain it twice and the build would fail with **CS0111**. So the usual contract between a library and its users is: 1. The user marks a type with the library's **marker attribute**, for example `[AutoDescribe]`. 2. The user declares the type `partial` (and, if the type is nested, every containing type too, for the same CS0260 reason). 3. Optionally the user writes **partial member declarations without bodies**, such as `public partial string Describe();`, and the generator supplies the bodies. ## A worked example ```csharp [AutoDescribe] public partial record struct Price(string Currency, decimal Amount) { public partial string Describe(); // body comes from the generator } ``` The generator reads the positional properties through the semantic model and adds a file containing: ```csharp partial record struct Price { public partial string Describe() => $"Price (Currency = {Currency}, Amount = {Amount})"; } ``` A record struct is a handy target for a second reason: the compiler synthesizes `ToString` only when no declaration of the type provides one, so a generated `public override string ToString()` in the generated part would be used instead of the synthesized one. ## When the target cannot be partial Some declarations can never be partial. `partial enum Status` is rejected with **CS0267**, because the modifier may appear only before `class`, `record`, `struct`, `interface`, `event`, an instance constructor name, or a method or property return type. A generator driven by `[FastNames]` on an enum therefore adds a **new type** instead, for example an `internal static class StatusNames` with an extension method `ToFastString(this Status value)` implemented as a `switch` over string literals. | Situation | What the generator emits | Why | |---|---|---| | Class, struct, record or record struct marked `partial` | Another `partial` declaration of the same type | Declarations merge into one type | | Partial member declared without a body | The implementing declaration | The user's declaration is the seam | | Enum or a type from another assembly | A new type, often with extension methods | That declaration cannot be extended | | Code the user already wrote | Nothing it can change | Generators are additive only | ## What it is not - **Not IL weaving or call-site rewriting.** Roslyn's design notes list optimisation, logging injection, IL weaving and call-site rewriting as code-altering operations outside what source generation is for. - **Not a way to add language features.** The same notes call implementing new syntax through a generator an anti-pattern, since it would create incompatible dialects of C#. - **Not run-time code.** Reflection discovers members while the process runs; a generator decided everything when the assembly was compiled.

  • Can a source generator change the body of a method you already wrote?
    No. Generators only add source. If the generated part declares a method with the same signature as yours, the merged type has two and the build fails with CS0111. The only methods a generator can fill are partial ones you declared without a body, such as `public partial string Describe();`. Changing existing behaviour needs a different seam you design in, not a rewrite.
  • How does a generator extend an enum marked [FastNames] when enums cannot be partial?
    `partial enum` is rejected with CS0267, so the generator adds a new type beside the enum instead, typically an `internal static class StatusNames` with an extension method `ToFastString(this Status value)` implemented as a `switch` over string literals. Callers write `status.ToFastString()` and never notice that the method lives on another type.
  • Does generated code cost anything extra when the program runs?
    No more than the same code typed by hand: it is parsed and compiled with the rest of the project into the same assembly. The cost moves to the build and the IDE, which run the generator on every compilation, so a slow generator shows up as slow builds and sluggish editing rather than slow start-up.

A contractor who may add rooms to your house only through doorways you have marked, and may never knock down or repaint a wall you built: partial is the marked doorway, and without it the contractor has nowhere to attach anything.

  • A source generator can rewrite or delete methods you already wrote.
  • Source generators run when the application starts, like reflection does.
  • Generated code is loaded or interpreted dynamically at run time.
  • A generator can add members to any class, partial or not.
  • Each generator reads and builds on the files earlier generators added.
open as a page

In C# 13 and 14, which partial members can a source generator implement, and what must the hand-written declaring declaration look like?

level: middleimportance: should knowfreq 24%

basics

~20 s

Methods have long been partial; C# 13 added properties and indexers, and C# 14 instance constructors and events. The user writes a bodiless declaring declaration with the exact signature, and the generator supplies the body.

open as a page

Your C# incremental generator's output step reruns after every unrelated edit in the IDE; why does a pipeline model holding an ISymbol defeat caching, and what fixes it?

level: seniorimportance: should knowfreq 20%

basics

~20 s

The driver skips downstream steps only when a step returns values equal to last run's. An ISymbol is a new object in every compilation, so it is never equal; return a record of strings and equatable collections instead.

open as a page

In a C# incremental source generator for [AutoDescribe], how do RegisterPostInitializationOutput, ForAttributeWithMetadataName and RegisterSourceOutput divide the work?

level: seniorimportance: should knowfreq 30%

basics

~10 s

RegisterPostInitializationOutput emits the fixed [AutoDescribe] attribute, ForAttributeWithMetadataName finds the types marked with it and turns each into a small model, and RegisterSourceOutput turns each model into a generated file with AddSource.

open as a page

A .NET app references your C# source generator project but sees no generated code; how must the generator be targeted, referenced and inspected?

level: seniorimportance: should knowfreq 18%

basics

~10 s

Target netstandard2.0, reference Microsoft.CodeAnalysis.CSharp privately, and reference the project with OutputItemType="Analyzer" and ReferenceOutputAssembly="false". Then check for CS9057 or CS8785 warnings and set EmitCompilerGeneratedFiles to see the output.

open as a page

As lead of a .NET library that maps types with runtime reflection at startup, would you replace that reflection with a C# source generator, and what would it cost?

level: principalimportance: should knowfreq 32%

basics

~20 s

Replace it when users need trimming, Native AOT or fast start-up and their types are known at compile time. The price: a Roslyn component to maintain, a partial-type contract, build and editor cost, and no run-time-only types.

open as a page