Skip to content
Search lessons, topics, tests…
Esc

    ↑ ↓ moveEnter openEsc close
    C# Source Generators: back to the course
    Lesson2 / 12

    Why an incremental generator must be deterministic

    Add an unrelated class: Parcel's generated method should stay the same. Rename Parcel to Shipment: it must change. Which pipeline value distinguishes those edits?

    In this generator, the output model is namespace plus type name. Discovery can run again and still produce that same value; equal output can stop downstream recomputation. Determinism means the same declared inputs yield the same model/source, not that the generator runs only once.

    Lesson video

    Keep input and equality visible

    Tempting shortcutWhy it breaks the model
    Clock, randomness or new GUID in a transformSame tracked input can produce a new result
    Read an undeclared file/environment valueThe compiler does not track that dependency
    Emit in incidental discovery orderIdentical semantic input can reorder output
    Keep symbols/arrays as the final modelEquality may reflect identity rather than emitted values

    Select small equatable values before expensive rendering. Records do not give arrays/lists element-by-element equality automatically. Sort aggregate output by a complete stable identity with an explicit comparison rule. Combine depends on both inputs; Collect creates an aggregate and should serve an actual aggregate output need.

    Key points to remember

    Pure transforms
    Same declared inputs must give the same model and the same source text No DateTime.Now, Guid.NewGuid or randomness in a transform
    Tracked inputs only
    Read files and options through the providers the compiler tracks AdditionalTextsProvider, AnalyzerConfigOptionsProvider
    Stable ordering
    Sort by a stable, sufficiently qualified key A.Item and B.Item are different keys
    Equatable models
    Carry only the values that affect output A (namespace, name) tuple, not symbols or compilations

    Quick check

    A generator needs statuses.names.txt to affect its output. Which input route makes that dependency visible to the compiler?

    A Read an undeclared path only from RegisterSourceOutput
    B Declare AdditionalFiles and consume AdditionalTextsProvider
    C Read DateTime.Now to detect whether a build is new
    D Store the previous file text in a static field
    Show answer

    Correct answer: B

    AdditionalFiles declares the external input, and AdditionalTextsProvider exposes it to the incremental pipeline.

    Option A: The direct read does not declare the dependency.

    Option C: Clock time is unrelated to the file change.

    Option D: Hidden mutable state is not a tracked compiler input.

    Contract reference: Microsoft documentation.

    Build the complete generator

    Use sibling Tin.Generator and Tin.App folders. The generator targets netstandard2.0, uses C# 12 and pins Roslyn 4.14.0 as its API baseline. A compatible compiler host is required; this is not a latest-package or every-IDE claim.

    Supported targets are top-level, non-generic, non-static, non-file-local partial classes. Records, nested types, repeated markers, a target named GeneratedName, and an existing GeneratedName member in its inheritance chain are rejected. Tin.GenerateNameAttribute is reserved for this example.

    Tin.Generator/Tin.Generator.csproj

    XML
    <Project Sdk="Microsoft.NET.Sdk">
      <PropertyGroup>
        <TargetFramework>netstandard2.0</TargetFramework>
        <LangVersion>12.0</LangVersion>
        <Nullable>enable</Nullable>
        <IsRoslynComponent>true</IsRoslynComponent>
      </PropertyGroup>
      <ItemGroup>
        <PackageReference Include="Microsoft.CodeAnalysis.CSharp" Version="4.14.0" PrivateAssets="all" />
      </ItemGroup>
    </Project>

    Tin.Generator/NameGenerator.cs

    Before running, locate the point where Candidate loses its source location and becomes only output-relevant values.

    C#
    using System;
    using System.Collections.Generic;
    using System.Globalization;
    using System.Linq;
    using System.Text;
    using System.Threading;
    using Microsoft.CodeAnalysis;
    using Microsoft.CodeAnalysis.CSharp;
    using Microsoft.CodeAnalysis.CSharp.Syntax;
    using Microsoft.CodeAnalysis.Text;
    
    namespace Tin.Generators;
    
    [Generator(LanguageNames.CSharp)]
    public sealed class NameGenerator : IIncrementalGenerator
    {
        private const string AttributeName = "Tin.GenerateNameAttribute";
        private static readonly DiagnosticDescriptor InvalidTarget = new(
            "TINSG001", "Unsupported generation target",
            "Type '{0}' must be a top-level, non-generic, non-static, non-file-local partial class, " +
            "whose name is not GeneratedName, with exactly one GenerateName attribute " +
            "and no GeneratedName member in its hierarchy",
            "Tin.SourceGeneration", DiagnosticSeverity.Error, isEnabledByDefault: true);
    
        public void Initialize(IncrementalGeneratorInitializationContext context)
        {
            context.RegisterPostInitializationOutput(static output => output.AddSource(
                "GenerateNameAttribute.g.cs", SourceText.From("""
                namespace Tin
                {
                    [global::System.AttributeUsage(global::System.AttributeTargets.Class,
                        AllowMultiple = false, Inherited = false)]
                    internal sealed class GenerateNameAttribute : global::System.Attribute { }
                }
                """, Encoding.UTF8)));
    
            var candidates = context.SyntaxProvider.ForAttributeWithMetadataName(
                AttributeName,
                static (node, _) => node is TypeDeclarationSyntax,
                static (target, token) => Analyze(target, token));
    
            // Keep locations in the diagnostic branch, not the value-equal source model.
            context.RegisterSourceOutput(candidates.Where(static item => !item.IsValid),
                static (output, item) => output.ReportDiagnostic(
                    Diagnostic.Create(InvalidTarget, item.Location, item.Name)));
    
            var models = candidates.Where(static item => item.IsValid)
                .Select(static (item, _) => (item.Namespace, item.Name))
                .WithTrackingName("TargetModel");
    
            context.RegisterSourceOutput(models, static (output, model) =>
            {
                string qualifiedName = (model.Namespace.Length == 0 ? "" :
                    model.Namespace.Replace("@", "") + ".") + model.Name;
                string body = "partial class @" + model.Name + "\n{\n" +
                    "    public static string GeneratedName() => " +
                    SymbolDisplay.FormatLiteral(qualifiedName, quote: true) + ";\n}\n";
                string source = model.Namespace.Length == 0 ? body :
                    "namespace " + model.Namespace + "\n{\n" + body + "}\n";
                // Roslyn compares hint names case-insensitively. Encode the full name
                // so legal C# case variants such as Parcel and parcel remain distinct.
                string hint = "Name_" + string.Concat(qualifiedName.Select(character =>
                    ((int)character).ToString("X4", CultureInfo.InvariantCulture))) +
                    ".GeneratedName.g.cs";
                output.AddSource(hint,
                    SourceText.From(source, Encoding.UTF8));
            });
        }
    
        private static Candidate Analyze(GeneratorAttributeSyntaxContext target,
            CancellationToken token)
        {
            token.ThrowIfCancellationRequested();
            var syntax = (TypeDeclarationSyntax)target.TargetNode;
            var symbol = (INamedTypeSymbol)target.TargetSymbol;
            bool supported = syntax is ClassDeclarationSyntax &&
                symbol.ContainingType is null && symbol.Arity == 0 && !symbol.IsStatic &&
                symbol.Name != "GeneratedName" &&
                symbol.DeclaringSyntaxReferences.All(reference =>
                {
                    token.ThrowIfCancellationRequested();
                    return reference.GetSyntax(token) is ClassDeclarationSyntax part &&
                        part.Modifiers.Any(SyntaxKind.PartialKeyword) &&
                        !part.Modifiers.Any(SyntaxKind.FileKeyword);
                }) &&
                symbol.GetAttributes().Count(attribute =>
                    attribute.AttributeClass?.ToDisplayString() == AttributeName) == 1;
    
            for (INamedTypeSymbol? type = symbol; type is not null; type = type.BaseType)
                supported &= type.GetMembers("GeneratedName").Length == 0;
    
            var namespaceParts = new Stack<string>();
            for (var space = symbol.ContainingNamespace; !space.IsGlobalNamespace;
                space = space.ContainingNamespace)
                namespaceParts.Push("@" + space.Name);
    
            return new Candidate(string.Join(".", namespaceParts), symbol.Name,
                supported, syntax.Identifier.GetLocation());
        }
    
        private sealed class Candidate
        {
            public Candidate(string ns, string name, bool isValid, Location location)
            {
                Namespace = ns;
                Name = name;
                IsValid = isValid;
                Location = location;
            }
    
            public string Namespace { get; }
            public string Name { get; }
            public bool IsValid { get; }
            public Location Location { get; }
        }
    }

    Read the pipeline in four passes

    1. Post-initialization contributes the marker declaration.
    2. Analyze validates supported shapes; invalid candidates lead to TINSG001.
    3. The successful branch projects to a namespace/name tuple, dropping diagnostic location before rendering.
    4. The emitter escapes identifiers/literals, uses fixed newlines and creates a collision-safe hint.
    Generator dependency map: post-init emits a marker separately. Marked declarations become candidates. Unsupported targets report TINSG001. Valid candidates project to namespace/name tuples without location. Equal tuples can reuse output; new or changed tuples render target source.

    NameGenerator emits its marker attribute through a separate post-initialization output. Marked declarations are analyzed into Candidate objects containing namespace, name, validity and location. An unsupported candidate reports TINSG001 at its type name and emits no target declaration. A supported candidate projects to the value tuple ("@Demo", "Parcel"), excluding location. Across retained-driver updates, equal selected values can reuse downstream target output; new or changed values, such as renaming Parcel to Shipment, trigger escaping, rendering and target AddSource. This is a dependency map, not a callback schedule.

    The full generator's hint uses fixed-width uppercase UTF-16 hexadecimal encoding, unlike lesson 1's narrow readable-name hint. That distinguishes A.Item/B.Item and Demo.Parcel/Demo.parcel under Roslyn 4.14.0's ordinal case-insensitive hint comparison. Do not swap the two implementations when running lesson 3's exact-hint tests. In the tested Roslyn 4.14.0 and 5.9.0, Parcel.g.cs and parcel.g.cs collide; the pinned comparison source explicitly uses OrdinalIgnoreCase. Recheck these implementation assumptions when updating the lab’s compiler.

    Tin.App/Tin.App.csproj

    XML
    <Project Sdk="Microsoft.NET.Sdk">
      <PropertyGroup>
        <OutputType>Exe</OutputType>
        <TargetFramework>net10.0</TargetFramework>
        <LangVersion>12.0</LangVersion>
        <Nullable>enable</Nullable>
        <EmitCompilerGeneratedFiles>true</EmitCompilerGeneratedFiles>
      </PropertyGroup>
      <ItemGroup>
        <ProjectReference Include="../Tin.Generator/Tin.Generator.csproj"
            OutputItemType="Analyzer" ReferenceOutputAssembly="false" />
      </ItemGroup>
    </Project>

    Use the previous lesson's complete consumer. From the common parent folder:

    Text
    dotnet build Tin.App/Tin.App.csproj
    dotnet run --project Tin.App/Tin.App.csproj --no-build

    Expect Demo.Parcel. The type hint is Name_00440065006D006F002E00500061007200630065006C.GeneratedName.g.cs; the marker remains GenerateNameAttribute.g.cs. Inspect current driver output or generated copies without adding those files back as manual source.

    Try before checking

    Predict the model and diagnostic/source changes for the three edits below. Hint: separate discovery work from final value equality. Check: an invalid target loses its generated declaration; an unchanged name model need not rerun its expensive output.

    Three changes to reason through

    1. Add an unrelated class. Discovery may do work again, but this example still extracts the same namespace/name tuple for Parcel. The generated method should be identical. This is the boundary worth measuring.
    2. Remove partial from Parcel. This is no longer a supported target. TINSG001 should identify its name, and the extra Parcel declaration should not be emitted. A remaining call to GeneratedName can also produce a normal compiler error; do not suppress it to preserve a false successful build.
    1. Add Demo.parcel beside Demo.Parcel, both marked and partial. Both are valid distinct C# types. Their encoded hints differ (0050 for P, 0070 for p), so neither overwrites nor conflicts with the other. Include this as a regression test; checking different namespaces alone would miss the case-insensitive hint collision.

    Unsupported user input deserves a located diagnostic, not a hidden exception or conflicting class. Honor callback cancellation. Test reproducibility with a fresh driver and reuse with a retained driver; one does not establish the other.

    Practice

    Sign in to mark lessons done and keep your place in the course.Sign in

    TechInterviewNotes Editorial Team · Updated 27 Oct 2026 ·