Source generators
A source generator is a program the compiler runs during a build. It reads the source and the metadata of the project and writes more C# into the compilation, which the compiler then compiles as if the programmer had typed it. The .NET SDK carries several generators, so a program can use one without NuGet and without the network; the JSON generator is the one this lesson runs.
What a source generator is
A generator is an analyzer with a different output: instead of reporting a diagnostic, it adds source. The analyzers and generators of the SDK live in the targeting packs and run as part of every dotnet build. Three consequences follow, and the rest of this lesson is one of them:
- The generated code is visible in the build output when the project asks for it, which makes it debuggable.
- The generator runs on the machine that builds, so a generator from NuGet needs a restore, and a restore needs the network or a package cache.
- A generator cannot change the code the programmer wrote; it can only add partial declarations, which is why the types it fills in are partial.
The JSON generator in the SDK
System.Text.Json can write the serialization code at build time. The programmer declares a partial class derived from JsonSerializerContext and lists the types with [JsonSerializable]; the generator writes the rest, including a property per type:
using System.Text.Json;
using System.Text.Json.Serialization;
var order = new Order(1, "Ada");
var json = JsonSerializer.Serialize(order, SourceContext.Default.Order);
Console.WriteLine(json);
var back = JsonSerializer.Deserialize(json, SourceContext.Default.Order)!;
Console.WriteLine($"back {back.Id} {back.Customer}");
[JsonSerializable(typeof(Order))]
internal partial class SourceContext : JsonSerializerContext
{
}
internal sealed record Order(int Id, string Customer);
dotnet run
{"Id":1,"Customer":"Ada"}
back 1 Ada
The call names SourceContext.Default.Order, a property the generator wrote; without the generator the class has no such member and the build fails. The JSON keeps the property names of the record, because the options of a context are its own: the lesson on writing JSON showed the camelCase policy, and a context is configured with JsonSourceGenerationOptions when a different naming is wanted. The round trip returned the same two values.
The generated files
By default the generated sources live in memory. The project property EmitCompilerGeneratedFiles writes them under obj:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<EmitCompilerGeneratedFiles>true</EmitCompilerGeneratedFiles>
</PropertyGroup>
</Project>
find obj -path '*generated*' -name '*.cs'
obj/Debug/net10.0/generated/System.Text.Json.SourceGeneration/System.Text.Json.SourceGeneration.JsonSourceGenerator/SourceContext.g.cs
obj/Debug/net10.0/generated/System.Text.Json.SourceGeneration/System.Text.Json.SourceGeneration.JsonSourceGenerator/SourceContext.GetJsonTypeInfo.g.cs
obj/Debug/net10.0/generated/System.Text.Json.SourceGeneration/System.Text.Json.SourceGeneration.JsonSourceGenerator/SourceContext.PropertyNames.g.cs
obj/Debug/net10.0/generated/System.Text.Json.SourceGeneration/System.Text.Json.SourceGeneration.JsonSourceGenerator/SourceContext.Int32.g.cs
obj/Debug/net10.0/generated/System.Text.Json.SourceGeneration/System.Text.Json.SourceGeneration.JsonSourceGenerator/SourceContext.String.g.cs
obj/Debug/net10.0/generated/System.Text.Json.SourceGeneration/System.Text.Json.SourceGeneration.JsonSourceGenerator/SourceContext.Order.g.cs
Six files, one per generated type and one per primitive the order needs. They are build products and belong in obj, never in the repository; the lesson on the project file says the same about bin. A program that reads them sees exactly the code that runs, which is the point of the property when a generator does something surprising.
What needs a package
The generators of the SDK are the exception, not the rule. The popular ones, the mapper of a web framework, the client of an RPC system and the serializer of a database, come as NuGet packages with an analyzer inside, and a project that references one restores it before the build. This container has no network, so a project with such a package fails at restore with error NU1301, which the lesson on the CLI showed; there is no generated code to look at until the package is on the machine. On a machine with the network, the reference is one dotnet add package and the generator runs like the one above.
Exercises
- Add a second record to [JsonSerializable] and find its generated file.
- Give the context JsonSourceGenerationOptions with camelCase and run the first program again.
- Read the SourceContext.Order.g.cs file and find the code that writes the members.
- Remove the generator by deleting the context and read the compiler error of the call that used it.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
When does a source generator run?
Answer
During the build, inside the compiler
It adds source to the compilation, and the compiler then compiles it.
-
What does the JSON source generator fill in?
Answer
A partial JsonSerializerContext declared by the programmer
The partial class is the hook; the generator writes the other half.
-
What does this program print?
using System.Text.Json; using System.Text.Json.Serialization; var order = new Order(1, "Ada"); Console.WriteLine(JsonSerializer.Serialize(order, SourceContext.Default.Order)); [JsonSerializable(typeof(Order))] internal partial class SourceContext : JsonSerializerContext { } internal sealed record Order(int Id, string Customer);Answer
{"Id":1,"Customer":"Ada"}
The context keeps the property names, as the measured run printed.
-
What does [JsonSerializable(typeof(Order))] tell the generator?
Answer
Generate the metadata for Order
It is the list of types the context will handle.
-
What does this program print?
using System.Text.Json; using System.Text.Json.Serialization; var text = JsonSerializer.Serialize(new Order(2, "Bo"), SourceContext.Default.Order); var back = JsonSerializer.Deserialize(text, SourceContext.Default.Order)!; Console.WriteLine(back.Id); [JsonSerializable(typeof(Order))] internal partial class SourceContext : JsonSerializerContext { } internal sealed record Order(int Id, string Name);Answer
2
The round trip returns the id that was written.
-
Which property makes the generated sources visible on disk?
Answer
EmitCompilerGeneratedFiles
The measured project wrote six files under obj with it.
-
Where do the generated files go?
Answer
Under obj, with the other build products
They are build products and are not committed.
-
Why does a generator from NuGet need the network?
Answer
The package is restored before the build can use its analyzer
A restore without a cache fails with NU1301 in this container.
-
What does this program print?
using System.Text.Json; using System.Text.Json.Serialization; Console.WriteLine(JsonSerializer.Serialize(new Order(1, "Ada"), SourceContext.Default.Order)); [JsonSerializable(typeof(Order))] internal partial class SourceContext : JsonSerializerContext { } internal sealed record Order(int Id, string Customer);Answer
{"Id":1,"Customer":"Ada"}
Default is the property the generator adds to the context class.
-
Can a source generator change the body of a method the programmer wrote?
Answer
No, it can only add declarations such as a partial member
It adds source; the existing source stays what the programmer wrote.
The code on this page was built with the .NET SDK 10.0.303 and run on Alpine Linux 3.24.3 (x86_64) in a Docker container.
Article author: Arthur Isaev