Source generators and analyzers
Source generators and analyzers
A source generator runs during compilation and contributes generated C# source. An analyzer examines code and reports diagnostics. Neither is the same as ordinary application code executing after launch. A generated serializer can use compile-time type information instead of discovering all contracts through reflection at runtime.
Examples target the proposed C# 14 / .NET 10 console baseline (one independent Program.cs per example, nullable enabled). Expected outputs are reasoned, not executed. Source-generation examples require the standard SDK and its built-in generators; no extra packages or external services are used.
Serialize with generated metadata
The .NET SDK includes System.Text.Json source generation. A partial class derived from JsonSerializerContext, annotated with JsonSerializable, requests a generated serialization contract. Build with the standard SDK and its generator enabled; this example cannot be pasted into a runner that lacks generator support.
using System;using System.Text.Json;using System.Text.Json.Serialization;var item = new StockItem("A1", 4);string json = JsonSerializer.Serialize(item, InventoryJson.Default.StockItem);using var doc = JsonDocument.Parse(json);Console.WriteLine(doc.RootElement.GetProperty("Code").GetString());Console.WriteLine(doc.RootElement.GetProperty("Quantity").GetInt32());public record StockItem(string Code, int Quantity);[JsonSerializable(typeof(StockItem))]internal partial class InventoryJson : JsonSerializerContext { }The generator supplies the context members; the serializer is passed the generated contract explicitly. Checking fields avoids depending on property order.
Expected output (reasoned, not executed):
A14Deserialize through a generated context
Metadata-mode source generation supports reading and writing JSON contracts. The DTO still requires business validation: valid JSON syntax and matching types do not guarantee acceptable stock levels.
using System;using System.Text.Json;using System.Text.Json.Serialization;string json = "{\"Code\":\"B2\",\"Quantity\":-2}";var item = JsonSerializer.Deserialize(json, InventoryJson.Default.StockItem);Console.WriteLine(item is not null && item.Quantity >= 0 ? "valid" : "invalid");public record StockItem(string Code, int Quantity);[JsonSourceGenerationOptions(GenerationMode = JsonSourceGenerationMode.Metadata)][JsonSerializable(typeof(StockItem))]internal partial class InventoryJson : JsonSerializerContext { }The generated contract can deserialize the negative integer. Domain logic rejects it separately.
Expected output (reasoned, not executed):
invalidSeparate generated code from analysis
This ordinary C# program models the kind of explicit member a generator might contribute, without using a real generator. A partial class can be split across source files; the compiler combines its parts. An analyzer may report issues in code but does not execute this example or supply its missing members.
using System;Console.WriteLine(new ItemFormatter().Format("A1"));partial class ItemFormatter { }partial class ItemFormatter{ public string Format(string code) => "Stock: " + code;}Both declarations are manually written in this fixture. Actual generated-source inspection requires a build. In a reviewed project, EmitCompilerGeneratedFiles can persist generated source for inspection; keep output outside normal source globs to avoid double compilation.
Expected output (reasoned, not executed):
Stock: A1Common mistakes and edge cases
Do not assume that source generation always improves performance, removes all reflection or makes the app Native AOT compatible. Serialization fast-path generation alone is not a deserialization contract. Choose metadata mode when reading JSON, or generate both modes as appropriate. Unsupported fast-path options can fall back to metadata only when metadata is available. Verify the generated contract and publish diagnostics independently. Inspect diagnostics, generated code and published behavior. Analyzers and generators execute in the build environment, so review their provenance like executable dependencies. Roslyn incremental generators and custom analyzer implementation are separate advanced build-tool topics; no third-party packages are installed here.
Practice and recap
Add a bool Available property to a positional record in example 1, set it to true, and add a JSON field assertion. Explain which artifact must be generated during compilation.
Hint: The JsonSerializable target remains StockItem; inspect Available with GetBoolean.
Learning objective: Distinguish build-time generation from runtime reflection. See accompanying manual practice and knowledge check.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Source generators and analyzers — knowledge check
Apply the lesson concepts to the following scenarios.
When does a source generator normally run?
What is the usual role of an analyzer?
Why is InventoryJson declared partial?
What does the negative quantity example show?
Does the manually split ItemFormatter prove a generator ran?