Module 1 · Incremental source generators · Lesson 1 of 12
What a source generator actually emits
The app calls Demo.Parcel.GeneratedName(), but you never wrote that method. After renaming Parcel to Shipment, what should change in the current compilation?
The contract is small: a marked partial class gains one static method returning its qualified name. Generation adds another C# file before application compilation; it does not rewrite the typed file or run when the app starts.
The original reference model is retained here; use the input/output listings below to check the actual compiler behavior.
Think of a print shop that adds an appendix to your manuscript before binding.
Your manuscript Your hand-written .cs files
The generator reads them but never rewrites them.
The added appendix Generated .g.cs files
New source compiled together with your code.
The binding step The compiler
Everything is compiled into one assembly at build time.
Lesson video
Connect the compiler extension
A generator is a separate compiler-host project. For project-to-project use, supply analyzer metadata rather than an ordinary application assembly reference:
<ItemGroup>
<ProjectReference Include="..\Tin.Generator\Tin.Generator.csproj"
OutputItemType="Analyzer"
ReferenceOutputAssembly="false" />
</ItemGroup>OutputItemType selects the analyzer role; ReferenceOutputAssembly=false keeps that output out of ordinary consuming assembly references. The compiler/IDE host runs the generator.
Compare input, generated declaration and result
This consumer is complete once the generator from the next lesson is available. Do not paste the generated declaration into the app yourself.
using System;
Console.WriteLine(Demo.Parcel.GeneratedName());
namespace Demo
{
[Tin.GenerateName]
public partial class Parcel { }
}Expected generated class in the first lesson's narrow hint scheme, Demo.Parcel.GeneratedName.g.cs:
namespace @Demo
{
partial class @Parcel
{
public static string GeneratedName() => "Demo.Parcel";
}
}The @ prefixes escape identifiers. Both partial declarations contribute to the same type. After a successful build:
Demo.Parcel
Quick check
Where does the GeneratedName method come from in this example?
Show answer
Correct answer: C
The generator adds C# source. The user declaration and compatible generated partial declaration form one type.
Option A: The original user file is not rewritten.
Option B: Generation happens in the compiler host, not application startup.
Option D: This is source generation, not post-compilation IL rewriting.
Contract reference: Microsoft documentation.
To extend this existing class, its declarations must permit partial extension. A generator making an independent helper type has a different requirement. Prefer IIncrementalGenerator for new pipelines: Initialize declares inputs/transforms, and RegisterSourceOutput adds text with unique hints. Equality boundaries govern reuse; unrelated edits need not skip every earlier step.
Key points to remember
- What it adds
- New source files only; it never edits your files Demo.Parcel.GeneratedName.g.cs
- How it is referenced
- OutputItemType="Analyzer" and ReferenceOutputAssembly="false" ProjectReference to the generator project
- Which API to use
- Prefer IIncrementalGenerator for new generators Register a pipeline in Initialize
- Extending a type
- The user's declarations must be partial public partial class Parcel { }
Try: predict three builds
Before running the companion, write the expected behavior for Parcel, its rename to Shipment, then removal of the marker while the caller still invokes the method.
Hint: current generated compilation and diagnostic copies on disk are different things. Check: the renamed app returns Demo.Shipment; removing generation leaves a caller error rather than a stale member.
Check your understanding
- Does removing partial always prevent source generation? No. It prevents this generator from extending that existing class. Generators can instead produce independent helper types. The full implementation introduced in the next lesson reports TINSG001 for its unsupported targets. The deliberately narrow companion below only demonstrates the valid
Demoinput and skips non-partial declarations; it is not that full diagnostic implementation. - Why not edit the .g.cs file to change the returned name? It is derived output. Fix the input or generator, rebuild, and inspect the replacement output.
- Why can a generator compile while the application fails? The generator program and the text it emits are different programs. Both need checking. The third lesson compiles the user source together with the generated source.
The attached practice reinforces this lesson and retains two bridge questions about determinism and testing. Continue with the next two lessons for their focused practice.
Real-SDK companion: keep the scope small
This companion uses a netstandard2.0 generator and a real consumer build. It is deliberately narrower than lesson 2: only the shown top-level, non-generic partial class in the single-component Demo namespace, without an existing GeneratedName member. It silently skips non-partial declarations and is not the later diagnostic implementation. Nested/global/dotted/escaped/generic shapes and collisions need validation or more capable emission.
Generator project and source
Restore needs the pinned Roslyn package/dependencies or a populated cache.
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<LangVersion>12.0</LangVersion>
<Nullable>enable</Nullable>
<EnforceExtendedAnalyzerRules>true</EnforceExtendedAnalyzerRules>
<IsRoslynComponent>true</IsRoslynComponent>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.CodeAnalysis.CSharp" Version="4.14.0" PrivateAssets="all" />
</ItemGroup>
</Project>using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
namespace Tin.Generator;
[Generator]
public sealed class NameGenerator : IIncrementalGenerator
{
public void Initialize(IncrementalGeneratorInitializationContext context)
{
context.RegisterPostInitializationOutput(static ctx => ctx.AddSource("Tin.GenerateNameAttribute.g.cs", """
namespace Tin
{
[global::System.AttributeUsage(global::System.AttributeTargets.Class)]
internal sealed class GenerateNameAttribute : global::System.Attribute { }
}
"""));
var models = context.SyntaxProvider.ForAttributeWithMetadataName("Tin.GenerateNameAttribute",
static (node, _) => node is ClassDeclarationSyntax c && c.Modifiers.Any(SyntaxKind.PartialKeyword),
static (ctx, _) => (Namespace: ctx.TargetSymbol.ContainingNamespace.ToDisplayString(), Name: ctx.TargetSymbol.Name));
context.RegisterSourceOutput(models, static (spc, m) =>
spc.AddSource($"{m.Namespace}.{m.Name}.GeneratedName.g.cs", $$"""
namespace @{{m.Namespace}}
{
partial class @{{m.Name}}
{
public static string GeneratedName() => "{{m.Namespace}}.{{m.Name}}";
}
}
"""));
}
}Consumer project
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0</TargetFramework>
<EmitCompilerGeneratedFiles>true</EmitCompilerGeneratedFiles>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="../Tin.Generator/Tin.Generator.csproj"
OutputItemType="Analyzer" ReferenceOutputAssembly="false" />
</ItemGroup>
</Project>Harness layout and project
Use the consumer listing above for sample/App/Program.cs and the shortened generator for NameGenerator.cs. The compile exclusion prevents sample source from becoming harness source.
Harness/
Harness.csproj
Program.cs // harness below
sample/
Tin.Generator/
Tin.Generator.csproj // generator project above
NameGenerator.cs
App/
App.csproj // consumer project above
Program.cs // Demo.Parcel consumer above<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<Compile Remove="sample/**/*.cs" />
</ItemGroup>
</Project>Run dotnet run --project Harness.csproj from Harness. The program copies sample into a uniquely named temporary directory, invokes three builds and leaves that directory for inspection.
// A01: build a real generator project and a consumer with the .NET SDK, then look at what the
// compiler wrote to disk. Copies ./sample to a temp folder so nothing here inherits these settings.
using System.Diagnostics;
var work = Path.Combine(Path.GetTempPath(), "tin-a01-" + Guid.NewGuid().ToString("N"));
CopyDir(Path.Combine(Directory.GetCurrentDirectory(), "sample"), work);
Console.WriteLine("Working directory: " + work);
var app = Path.Combine(work, "App");
var generatedRoot = Path.Combine(app, "obj", "Debug", "net10.0", "generated");
BuildAndShow("Build 1: class Parcel");
var program = Path.Combine(app, "Program.cs");
File.WriteAllText(program, File.ReadAllText(program).Replace("Parcel", "Shipment"));
BuildAndShow("Build 2: Parcel renamed to Shipment");
File.WriteAllText(program, File.ReadAllText(program).Replace("[Tin.GenerateName]", ""));
Console.WriteLine("Build 3: attribute removed, caller unchanged");
var failed = Dotnet("build --nologo --verbosity quiet", app, allowFailure: true);
var errorLine = failed.Split('\n').FirstOrDefault(l => l.Contains("error CS"));
if (errorLine is null) Console.WriteLine(" no compiler error found; inspect build output");
else
{
int start = errorLine.IndexOf("error CS", StringComparison.Ordinal);
int end = errorLine.IndexOf(" [", start, StringComparison.Ordinal);
Console.WriteLine(" " + errorLine[start..(end < 0 ? errorLine.Length : end)].Trim());
}
void BuildAndShow(string label)
{
Console.WriteLine(label);
Dotnet("build --nologo --verbosity quiet", app);
foreach (var f in Directory.GetFiles(generatedRoot, "*.cs", SearchOption.AllDirectories).Order(StringComparer.Ordinal))
Console.WriteLine(" obj/.../generated/" + Path.GetRelativePath(generatedRoot, f));
Console.WriteLine(" app prints: " + Dotnet("run --no-build --no-restore --verbosity quiet", app).Trim());
}
static string Dotnet(string args, string dir, bool allowFailure = false)
{
var psi = new ProcessStartInfo("dotnet", args) { WorkingDirectory = dir, UseShellExecute = false, RedirectStandardOutput = true, RedirectStandardError = true };
psi.Environment["DOTNET_CLI_TELEMETRY_OPTOUT"] = "1";
using var p = Process.Start(psi)!;
// Drain both pipes concurrently so a full stderr pipe cannot deadlock stdout reading.
var stdout = p.StandardOutput.ReadToEndAsync();
var stderr = p.StandardError.ReadToEndAsync();
p.WaitForExit();
var output = stdout.GetAwaiter().GetResult() + stderr.GetAwaiter().GetResult();
if (p.ExitCode != 0 && !allowFailure) throw new Exception($"dotnet {args} failed:\n{output}");
return output;
}
static void CopyDir(string from, string to)
{
foreach (var f in Directory.GetFiles(from, "*", SearchOption.AllDirectories))
{
var rel = Path.GetRelativePath(from, f);
if (rel.Contains("bin" + Path.DirectorySeparatorChar) || rel.Contains("obj" + Path.DirectorySeparatorChar)) continue;
Directory.CreateDirectory(Path.GetDirectoryName(Path.Combine(to, rel))!);
File.Copy(f, Path.Combine(to, rel));
}
}Read the recorded build pattern
The original transcript is from SDK 10.0.401; paths and diagnostics can vary. Inspect exit codes and current compilation behavior rather than treating every path as a portable expected string.
Build 1: class Parcel obj/.../generated/Tin.Generator/Tin.Generator.NameGenerator/Demo.Parcel.GeneratedName.g.cs obj/.../generated/Tin.Generator/Tin.Generator.NameGenerator/Tin.GenerateNameAttribute.g.cs app prints: Demo.Parcel Build 2: Parcel renamed to Shipment obj/.../generated/Tin.Generator/Tin.Generator.NameGenerator/Demo.Parcel.GeneratedName.g.cs obj/.../generated/Tin.Generator/Tin.Generator.NameGenerator/Demo.Shipment.GeneratedName.g.cs obj/.../generated/Tin.Generator/Tin.Generator.NameGenerator/Tin.GenerateNameAttribute.g.cs app prints: Demo.Shipment Build 3: attribute removed, caller unchanged error CS0117: 'Shipment' does not contain a definition for 'GeneratedName'
Build 1 contributes marker plus Parcel. Build 2 compiles Shipment even if an old Parcel diagnostic file remains under obj. EmitCompilerGeneratedFiles writes inspection copies; with the default obj exclusion those copies are not the next compilation's inputs. Refresh the generated inspection folder when comparing renames. Build 3's CS0117 is the expected missing-member consequence.
Generated output remains ordinary C#. It can replace a particular reflection path, but does not by itself establish trimming/Native AOT support. Check emitted dependencies and the actual publish configuration separately.
Practice
TechInterviewNotes Editorial Team · Updated 27 Oct 2026 ·