Updated on

A source generator is code that the C# compiler runs during a build. It reads our project’s code and adds new C# files to the same compilation. We write one by implementing IIncrementalGenerator in a netstandard2.0 class library, and whatever it produces is compiled right along with our own code.

Traditionally, code generation in C# involved using external tools or templates to generate code before the compilation process, like the T4 template. However, with source generators, code generation becomes an integral part of the compilation itself.

We’ll build two generators, a hello-world one and a service generator that renders Scriban templates. Then we’ll debug them, test them, and make sure they don’t slow the build down.

To download the source code for this article, you can visit our GitHub repository.

Let’s start.

What Are Source Generators in C#?

A source generator is a piece of code that the C# compiler runs during a build. It reads our code through the same syntax trees and semantic model the compiler uses, and it adds new C# files to the compilation. Those files are compiled together with our own, so we can call what the generator produced as if we had written it ourselves.

Microsoft Learn describes the goal as “compile time metaprogramming, that is, code that can be created at compile time and added to the compilation.”

A generator can only add code. It can’t change or delete anything we wrote. It also runs inside the compiler, in Visual Studio as we type and in dotnet build, so a slow generator slows down everyone who uses it.

Source generators arrived as a compiler feature with .NET 5. Today we write them by implementing IIncrementalGenerator, because the Roslyn team has deprecated the older ISourceGenerator interface.

How Do We Set Up a Source Generator Project?

First, we should create a C# project that targets netstandard2.0 and add the package that gives us the source generator types.

We can start by creating a class library. Then, through the SDK, we can create a solution and a project in the current folder:

dotnet new sln -n SourceGeneratorInCSharp --format sln
dotnet new classlib --framework "netstandard2.0" -o ./Generator
dotnet sln add ./Generator

Afterward, we need to replace the content of Generator.csproj:

<Project Sdk="Microsoft.NET.Sdk">
    <PropertyGroup>
        <TargetFramework>netstandard2.0</TargetFramework>
        <IncludeBuildOutput>false</IncludeBuildOutput>
        <LangVersion>latest</LangVersion>
        <IsRoslynComponent>true</IsRoslynComponent>
        <EnforceExtendedAnalyzerRules>true</EnforceExtendedAnalyzerRules>
    </PropertyGroup>

    <ItemGroup>
        <PackageReference Include="Microsoft.CodeAnalysis.CSharp"
            Version="5.9.0"
            PrivateAssets="all" />
    </ItemGroup>
</Project>

IsRoslynComponent tells Visual Studio this project is a compiler extension, and EnforceExtendedAnalyzerRules turns on stricter analyzer rules for generator code, such as the ban on file IO. Another rule, on by default, is why we reference Microsoft.CodeAnalysis.CSharp and not the Workspaces package: with Workspaces, every generator gets warning RS1038, because the command-line compiler doesn’t load that assembly.

Which version of the package should we pick? The newest one isn’t always safe, because the compiler loads our generator, and the package can’t be newer than the compiler that runs the build. The .NET 11.0.100 SDK ships compiler version 5.12, so 5.9.0, the newest stable package today, loads fine. If we build the same generator with the .NET 10.0.301 SDK, whose compiler is version 5.6, it gets refused:

CSC : warning CS9057: Analyzer assembly 'Generator.dll' cannot be used because it references version '5.9.0.0' of the compiler, which is newer than the currently running version '5.6.0.0'.

It is only a warning, so it’s easy to miss. The build then fails with CS0246 errors in our own code, because the types the generator should have added aren’t there. When a generator stops working after a package update or on a CI agent with an older SDK, this warning is the first thing to look for.

As we know, source code generators work like an analyzer and provide an option to generate source code at development time even if the code cannot be compiled. For this, we need a separate project to reference our generator.

Let’s create a console application for this:

dotnet new console --framework "net11.0" -o SourceGeneratorInCSharp
dotnet sln add SourceGeneratorInCSharp

In the SourceGeneratorInCSharp.csproj we need to change the content:

<Project Sdk="Microsoft.NET.Sdk">
    <PropertyGroup>
        <OutputType>Exe</OutputType>
        <TargetFramework>net11.0</TargetFramework>
        <ImplicitUsings>enable</ImplicitUsings>
        <Nullable>enable</Nullable>
    </PropertyGroup>

    <ItemGroup>
        <ProjectReference Include="..\Generator\Generator.csproj"
            OutputItemType="Analyzer"
            ReferenceOutputAssembly="false" />
    </ItemGroup>
</Project>

So far, everything we’ve done has been pretty much standard stuff, so let’s get into the code.

Implementing a Simple Generator

A source generator has two defining characteristics, implementing the IIncrementalGenerator interface and decorating with the [Generator] attribute, which makes a project consider a class as a source generator:

[Generator]
public sealed class ExampleGenerator : IIncrementalGenerator
{
    public void Initialize(IncrementalGeneratorInitializationContext context)
    {
    }
}

The generator only requires the implementation of a single method, Initialize. In this method, we can register our static source code as well as create a pipeline to identify the syntax of interest and transform this syntax into source code.

We implement IIncrementalGenerator and not the older ISourceGenerator, which the Roslyn team has deprecated. With ISourceGenerator, a new ISyntaxReceiver is created for every generation, and the whole generator runs again. With bigger projects, this can quickly lead to performance issues in the editor. An incremental generator describes a pipeline instead, and the compiler caches the result of each step, so unchanged input means no work.

Now, let’s implement a generator that will output a simple source code:

using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Text;
using System.Text;

[Generator]
public sealed class ExampleGenerator : IIncrementalGenerator
{
    public void Initialize(IncrementalGeneratorInitializationContext context)
    {
        context.RegisterPostInitializationOutput(ctx =>
        {
            var sourceText = $$"""
                namespace SourceGeneratorInCSharp
                {
                    public static class HelloWorld
                    {
                        public static void SayHello()
                        {
                            Console.WriteLine("Hello From Generator");
                        }
                    }
                }
                """;

            ctx.AddSource("ExampleGenerator.g", SourceText.From(sourceText, Encoding.UTF8));
        });
    }
}

In the example, we use a string literal to represent the code we want to emit.

The RegisterPostInitializationOutput only allows us to add fixed source code, as we don’t have any access to the user code at this point.

To emit the files, we utilize the AddSource() method, which requires two parameters. The first parameter serves as a distinct identifier for the emitted source, while the second parameter represents the actual source text. This text is obtained from our hard-coded string and includes the corresponding encoding information.

After we build, if everything is set up properly, we can see the generated code file under the analyzer in the Console project solution explorer:

Generated file from SourceGenerators in C#

If we double-click the ExampleGenerator.g.cs we can see the output code, including warnings from Visual Studio that this file isn’t editable:

Code generated from Source Generators in C#

Implementing a More Complex Generator

Now that we’ve seen how a generator works through a simple example, let’s tackle something different. Before we build a more complex generator, let’s consider a scenario for our practice.

For many corporate applications, we have a series of architectural patterns that are followed, such as the use of entities, repositories, services, and controllers, most of which have the same implementation. This tends to be a very manual and time-consuming task. The code we need to write to create the entire structure tends to be repetitive and error-prone.

Using C# source code generators to generate some of these parts can save us a lot of time. So let’s implement the service class as an example.

Adding a Marker Attribute

We need to think about how we are going to choose which models we are going to generate service classes for. We can do this for all models in the project, but that would cause services to be generated even for the models we don’t need. For that, we can use a marker attribute. A marker attribute is a simple attribute that has no functionality and exists only to be located. If attributes are new to you, our article on custom attributes in .NET shows how they are declared and read.

We’re going to create a simple marker attribute, but we’re not going to define this attribute directly in the code. Instead, we will create a string containing C# code for the [GenerateService] attribute. We will have the generator automatically add this to the build of the consuming project, so the attribute becomes part of that project. It is necessary to do this because when referencing our Generator project we set the ReferenceOutputAssembly to false.

If ReferenceOutputAssembly is set to false, the output of the referenced project is not included as a Reference of this project, but it is still guaranteed that the other project builds before this one.

Let’s create the attribute:

public static class SourceGenerationHelper
{
    public const string Attribute = """
        namespace Generator
        {
            [System.AttributeUsage(System.AttributeTargets.Class)]
            [Microsoft.CodeAnalysis.Embedded]
            internal sealed class GenerateServiceAttribute : System.Attribute
            {
            }
        }
        """;
}

The attribute is internal and carries [Microsoft.CodeAnalysis.Embedded]. Every project that uses our generator gets its own copy of the attribute, and when one of those projects can see another’s internals, the copies clash and the compiler warns. The Embedded marker tells the compiler to ignore a copy that comes from another assembly. We add the EmbeddedAttribute type itself in the next step. It needs Roslyn 4.14 or newer, which every current SDK has.

Creating the Source Generator

As mentioned earlier, our starting point is a class that implements the IIncrementalGenerator interface and is decorated with the [Generator] attribute:

[Generator]
public sealed class ServiceGenerator : IIncrementalGenerator
{
    public void Initialize(IncrementalGeneratorInitializationContext context)
    {
        context.RegisterPostInitializationOutput(ctx =>
        {
            ctx.AddEmbeddedAttributeDefinition();
            ctx.AddSource(
                "GenerateServiceAttribute.g.cs",
                SourceText.From(SourceGenerationHelper.Attribute, Encoding.UTF8));
        });
    }
}

In the implementation, we used the RegisterPostInitializationOutput method, which allows us to register a callback that will be called once. It’s useful for efficiently adding “constant” sources to the build, like our marker attribute and the EmbeddedAttribute it relies on. Now we have the attribute available for use in our SourceGeneratorInCSharp project.

Development of the Generator Pipeline

Now we need a pipeline that finds our classes and turns each of them into source code. The compiler memoizes the result of every stage, so it doesn’t redo the work when nothing has changed:

using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;
using Scriban;
using System.IO;
using System.Text;

[Generator]
public sealed class ServiceGenerator : IIncrementalGenerator
{
    private static readonly Template ServiceTemplate =
        Template.Parse(GetEmbeddedResource("Generator.Templates.Service.scriban"));

    public void Initialize(IncrementalGeneratorInitializationContext context)
    {
        context.RegisterPostInitializationOutput(ctx =>
        {
            ctx.AddEmbeddedAttributeDefinition();
            ctx.AddSource(
                "GenerateServiceAttribute.g.cs",
                SourceText.From(SourceGenerationHelper.Attribute, Encoding.UTF8));
        });

        IncrementalValuesProvider<ServiceModel> models = context.SyntaxProvider
            .ForAttributeWithMetadataName(
                "Generator.GenerateServiceAttribute",
                predicate: static (node, _) => IsSyntaxTargetForGeneration(node),
                transform: static (ctx, _) => GetTargetForGeneration(ctx));

        context.RegisterSourceOutput(models,
            static (spc, model) => Execute(model, spc));
    }
}

In the first stage, ForAttributeWithMetadataName takes the full metadata name of our attribute and finds every syntax node that carries it. The compiler does most of that filtering itself, before our code runs. The predicate, IsSyntaxTargetForGeneration, is a second filter on what’s left, and the transform, GetTargetForGeneration, turns each match into a small ServiceModel.

In the second stage, RegisterSourceOutput calls our Execute method once for every model.

We’ll come back to why this shape matters for performance after the tests are in place.

Implementing the Stages

The IsSyntaxTargetForGeneration predicate checks if the given SyntaxNode is relevant to our generator.

Syntax nodes are one of the main elements of syntax trees. These nodes represent declarations, statements, clauses, and expressions. Each category of syntax nodes is represented by a separate class derived from Microsoft.CodeAnalysis.SyntaxNode:

public static bool IsSyntaxTargetForGeneration(SyntaxNode syntaxNode)
    => syntaxNode is ClassDeclarationSyntax;

Since ForAttributeWithMetadataName already found the attribute for us, all that’s left to check is that the node is a class. There’s no attribute name to compare as a string anymore.

In the transformation stage, we get a GeneratorAttributeSyntaxContext. Its TargetSymbol is the class as the compiler understands it. A symbol represents a declared code element and provides information about its properties, including its name, containing namespace, and containing assembly. We copy those three values, plus the location of the class name, into a model:

public static ServiceModel GetTargetForGeneration(GeneratorAttributeSyntaxContext context)
{
    var symbol = context.TargetSymbol;
    var location = context.TargetNode is ClassDeclarationSyntax classSyntax
        ? classSyntax.Identifier.GetLocation()
        : symbol.Locations[0];

    return new ServiceModel(
        ClassName: symbol.Name,
        ClassNamespace: symbol.ContainingNamespace.ToDisplayString(),
        ClassAssembly: symbol.ContainingAssembly.Name,
        Location: LocationInfo.From(location));
}

The model is a record struct, so two models with the same values are equal:

using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Text;

public readonly record struct ServiceModel(
    string ClassName,
    string ClassNamespace,
    string ClassAssembly,
    LocationInfo Location);

public readonly record struct LocationInfo(string FilePath, TextSpan Span, LinePositionSpan LineSpan)
{
    public Location ToLocation() => Location.Create(FilePath, Span, LineSpan);

    public static LocationInfo From(Location location)
        => new(location.SourceTree?.FilePath ?? string.Empty,
            location.SourceSpan,
            location.GetLineSpan().Span);
}

Why not pass the symbol or the syntax node along? Because a symbol never compares equal from one build to the next, and a syntax node stops comparing equal once its file is edited, so the compiler often couldn’t tell that nothing has changed. LocationInfo exists for the same reason: a Location holds on to the syntax tree, while a file path and two spans are plain values. Records on netstandard2.0 need the IsExternalInit type, which the PolySharp package (we install it in the next section) adds for us.

Working With Templates

Before starting work on the Execute method, let’s create a template to use for code generation. A simple string builder would suffice, however, we can use a template engine. At this point, we can use the Scriban template engine.

Scriban is a fast, robust, safe and lightweight scripting language and engine for .NET. By adopting this approach, we can store the templates in individual files, thereby maintaining a well-organized solution.

To use this template tool we need a few more settings and packages. Let’s inspect the full Generator.csproj file:

<Project Sdk="Microsoft.NET.Sdk">
	<PropertyGroup>
		<TargetFramework>netstandard2.0</TargetFramework>
		<IncludeBuildOutput>false</IncludeBuildOutput>
		<LangVersion>latest</LangVersion>
		<Nullable>enable</Nullable>
		<IsRoslynComponent>true</IsRoslynComponent>
		<EnforceExtendedAnalyzerRules>true</EnforceExtendedAnalyzerRules>
		<PackageScribanIncludeSource>true</PackageScribanIncludeSource>
		<PolySharpIncludeRuntimeSupportedAttributes>true</PolySharpIncludeRuntimeSupportedAttributes>
		<NoWarn>$(NoWarn);RS2008</NoWarn>
	</PropertyGroup>

	<ItemGroup>
		<PackageReference Include="Microsoft.CodeAnalysis.CSharp" Version="5.9.0" PrivateAssets="all" />
		<PackageReference Include="Microsoft.CSharp" Version="4.7.0" />
		<PackageReference Include="Scriban" Version="7.6.1" IncludeAssets="Build" />
		<PackageReference Include="System.Threading.Tasks.Extensions" Version="4.6.3" />
		<PackageReference Include="PolySharp" Version="1.17.1" PrivateAssets="all" IncludeAssets="runtime; build; native; contentfiles; analyzers" />
	</ItemGroup>

	<ItemGroup>
		<None Remove="Templates\**\*.scriban" />
		<EmbeddedResource Include="Templates\**\*.scriban" />
	</ItemGroup>
</Project>

The compiler loads our generator assembly, but not the NuGet packages it depends on. So instead of referencing the Scriban DLL, we compile Scriban’s source code into the generator. PackageScribanIncludeSource turns that on, and IncludeAssets="Build" keeps the DLL itself out. Without the property, the generator doesn’t even compile, because the Scriban types aren’t there. On netstandard2.0, Scriban’s documentation also asks for nullable annotations, PolySharp, Microsoft.CSharp and System.Threading.Tasks.Extensions. RS2008 is an analyzer-release-tracking warning that our diagnostic would raise, and it doesn’t matter for a sample.

Now, let’s create a file named Service.scriban inside the Templates folder, with the content:

using System.Collections.Generic;
using System.Linq;
using {{class_namespace}};

namespace {{class_assembly}}.Services
{
    public partial class {{class_name}}Service
    {
        private static readonly List<{{class_name}}> _list = new();

        public virtual List<{{class_name}}> All()
        {
            return _list;
        }

        public virtual void Add({{class_name}} item)
        {
            _list.Add(item);
        }

        public virtual void Update({{class_name}} item)
        {
            var existing = _list.Single(x => x.Id == item.Id);

            _list.Remove(existing);
            _list.Add(item);
        }

        public virtual void Delete(int id)
        {
            var existing = _list.Single(x => x.Id == id);

            _list.Remove(existing);
        }
    }
}

The two System usings are there because the generated file is compiled in someone else’s project, and we can’t count on that project having implicit usings turned on.

The full Generator.csproj above already marks the file as an embedded resource, with these lines:

<ItemGroup>
    <None Remove="Templates\**\*.scriban" />
    <EmbeddedResource Include="Templates\**\*.scriban" />
</ItemGroup>

Development of Source Generators

After doing that, we can go back to our Execute method in ServiceGenerator and implement it:

public static void Execute(ServiceModel model, SourceProductionContext context)
{
    if (!model.ClassName.Contains("Model"))
    {
        var error = Diagnostic.Create(DiagnosticsDescriptors.ClassWithWrongNameMessage,
            model.Location.ToLocation(),
            model.ClassName);

        context.ReportDiagnostic(error);

        return;
    }

    var sourceCode = ServiceTemplate.Render(new
    {
        model.ClassName,
        model.ClassNamespace,
        model.ClassAssembly
    });

    context.AddSource(
        $"{model.ClassName}Service.g.cs",
        SourceText.From(sourceCode, Encoding.UTF8));
}

private static string GetEmbeddedResource(string path)
{
    using var stream = typeof(ServiceGenerator).Assembly.GetManifestResourceStream(path)!;
    using var streamReader = new StreamReader(stream);

    return streamReader.ReadToEnd();
}

Execute gets one model at a time, so a class with a wrong name only stops its own service, not the others.

The GetEmbeddedResource method retrieves the template string from the embedded resource, and we parse it once, in the ServiceTemplate field we saw earlier. We use the Template.Parse method to prepare our template for rendering and through the Render method we get our generated source code. Scriban turns ClassName into class_name and so on, which is the naming the template uses.

Finally, the generated source code is added to the compilation using context.AddSource. The method takes a name for the generated file (constructed from the class name) and the source code is represented as SourceText.

Debugging Source Generators

When developing source generators, we often need to debug the generators themselves. Since these generators run during the build process, we can’t debug them like casual C# projects, so we have to debug them some other way. If we want to attach our debugger to the compiler, the generator will run so fast that we won’t have enough time for that. Then we can use another trick, we can just wait until the debugger is attached.

At the beginning of the methods, add code to launch the debugger, with using System.Diagnostics; at the top of the file:

public static void Execute(ServiceModel model, SourceProductionContext context)
{
    Debugger.Launch();
    ...
}

We need to remove that line again before we commit, or every build will try to start a debugger. Visual Studio also has a cleaner way: with IsRoslynComponent in the generator’s project file, we can add a debug profile of the type “Roslyn Component” that points at the consuming project, and then press F5 on the generator itself.

Emitting Diagnostic Messages

Sometimes we may want to provide some diagnostic feedback to the developer to let them know when things aren’t going as expected. The context provided in the Execute method provides the context.ReportDiagnostic method, used to log diagnostic messages.

A diagnostic entity requires a message, message type, title, diagnostic code, and category, and it can also take a help link. The location is optional to identify the exact location of the problem in the source code, and we can pass optional arguments for the descriptor.

To keep things clean, we can store diagnostic descriptors in a separate static class:

using Microsoft.CodeAnalysis;

public static class DiagnosticsDescriptors
{
    public static readonly DiagnosticDescriptor ClassWithWrongNameMessage
        = new("ERR001",                                         // id
            "Wrong name",                                       // title
            "The class '{0}' must contain 'Model' in its name", // message
            "Generator",                                        // category
            DiagnosticSeverity.Error,
            true);
}

To report a diagnostic message we just call ReportDiagnostic method:

public static void Execute(ServiceModel model, SourceProductionContext context)
{
    if (!model.ClassName.Contains("Model"))
    {
        var error = Diagnostic.Create(DiagnosticsDescriptors.ClassWithWrongNameMessage,
            model.Location.ToLocation(),
            model.ClassName);

        context.ReportDiagnostic(error);

        return;
    }
    ...
}

The Roslyn cookbook doesn’t recommend reporting diagnostics from a generator, because doing it without breaking incrementality is hard. For a rule like our naming check, a separate Roslyn analyzer is the cleaner home. We keep it in the generator because it shows the API, and because our model carries the location as plain values, the pipeline still caches.

Executing Source Generators

We’re done with the Generator project, so now let’s get it working.

There is still no service in our Analyzers because we don’t use the [GenerateService] attribute yet. Let’s start by creating a new model with our attribute, called PersonModel:

using Generator;

namespace SourceGeneratorInCSharp.Models
{
    [GenerateService]
    public class PersonModel
    {
        public int Id { get; set; }

        public string? Name { get; set; }
    }
}

The project needs to be built and upon completion, we will see the generated code in the Solution Explorer analyzer:

using System.Collections.Generic;
using System.Linq;
using SourceGeneratorInCSharp.Models;

namespace SourceGeneratorInCSharp.Services
{
    public partial class PersonModelService
    {
        private static readonly List<PersonModel> _list = new();

        public virtual List<PersonModel> All()
        {
            return _list;
        }

        public virtual void Add(PersonModel item)
        {
            _list.Add(item);
        }

        public virtual void Update(PersonModel item)
        {
            var existing = _list.Single(x => x.Id == item.Id);

            _list.Remove(existing);
            _list.Add(item);
        }

        public virtual void Delete(int id)
        {
            var existing = _list.Single(x => x.Id == id);

            _list.Remove(existing);
        }
    }
}

With the PersonModelService generated, let’s use it:

namespace SourceGeneratorInCSharp
{
    using Services;

    public class Program
    {
        public static void Main(string[] args)
        {
            var personModelService = new PersonModelService();

            personModelService.Add(new() { Id = 1, Name = "Mathew" });
            personModelService.All().ForEach(x => Console.WriteLine(x.Name));
        }
    }
}

Testing Source Generators

Testing is a very important part of every developer process and as you might expect, writing code generators is no exception.

Let’s create an MSTest project, add it to the current solution, and give it a reference to the generator and to the Roslyn compiler package:

dotnet new mstest -o Tests
dotnet sln add Tests
dotnet add Tests reference Generator
dotnet add Tests package Microsoft.CodeAnalysis.CSharp --version 5.9.0

Before creating the test, we need a helper that compiles a piece of source code, runs our generator over it, and gives us back the generated files:

using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;

public static class Helper
{
    public static CSharpCompilation CreateCompilation(string sourceCode)
    {
        var syntaxTree = CSharpSyntaxTree.ParseText(sourceCode);

        var references = AppDomain.CurrentDomain.GetAssemblies()
            .Where(assembly => !assembly.IsDynamic)
            .Select(assembly => MetadataReference.CreateFromFile(assembly.Location));

        return CSharpCompilation.Create("SourceGeneratorTests",
            [syntaxTree],
            references,
            new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary));
    }

    public static GeneratorRunResult RunGenerator(string sourceCode)
    {
        GeneratorDriver driver = CSharpGeneratorDriver.Create(new ServiceGenerator());

        driver = driver.RunGenerators(CreateCompilation(sourceCode));

        return driver.GetRunResult().Results.Single();
    }

    public static string? GetGeneratedOutput(string sourceCode, string hintName)
    {
        return RunGenerator(sourceCode).GeneratedSources
            .SingleOrDefault(source => source.HintName == hintName)
            .SourceText?.ToString();
    }
}

We ask the driver for its run result and pick the generated file by its hint name. That keeps the test working when the generator adds more files, and we just added one, EmbeddedAttribute.

After that, we can create the test:

using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;

[TestClass]
public class SourceGeneratorsUnitTest
{
    private const string PersonModelSource = """
        using Generator;

        namespace SourceGeneratorInCSharp.Models
        {
            [GenerateService]
            public class PersonModel
            {
                public int Id { get; set; }

                public string? Name { get; set; }
            }
        }
        """;

    [TestMethod]
    public void WhenGeneratePersonModelService_ThenReturnCorrectOutput()
    {
        var expectedResult = """
            using System.Collections.Generic;
            using System.Linq;
            using SourceGeneratorInCSharp.Models;

            namespace SourceGeneratorTests.Services
            {
                public partial class PersonModelService
                {
                    private static readonly List<PersonModel> _list = new();

                    public virtual List<PersonModel> All()
                    {
                        return _list;
                    }

                    public virtual void Add(PersonModel item)
                    {
                        _list.Add(item);
                    }

                    public virtual void Update(PersonModel item)
                    {
                        var existing = _list.Single(x => x.Id == item.Id);

                        _list.Remove(existing);
                        _list.Add(item);
                    }

                    public virtual void Delete(int id)
                    {
                        var existing = _list.Single(x => x.Id == id);

                        _list.Remove(existing);
                    }
                }
            }
            """;

        var output = Helper.GetGeneratedOutput(PersonModelSource, "PersonModelService.g.cs");

        Assert.AreEqual(expectedResult.ReplaceLineEndings(), output?.ReplaceLineEndings().TrimEnd());
    }
}

The namespace is SourceGeneratorTests.Services because the test compilation is called SourceGeneratorTests. ReplaceLineEndings() is there because the template’s line endings depend on how Git checked it out. TrimEnd() drops the newline that many editors add at the end of the template file.

We can test the diagnostic the same way. A class without “Model” in its name should give us ERR001 and no service:

[TestMethod]
public void WhenClassNameHasNoModel_ThenReportErr001()
{
    var input = """
        using Generator;

        [GenerateService]
        public class Person
        {
            public int Id { get; set; }
        }
        """;

    var result = Helper.RunGenerator(input);

    var diagnostic = result.Diagnostics.Single();
    Assert.AreEqual("ERR001", diagnostic.Id);
    Assert.IsEmpty(result.GeneratedSources.Where(s => s.HintName == "PersonService.g.cs"));
}

After all of this, we can go ahead and explain some additional points.

How Do We Keep a Source Generator Fast?

We keep a source generator fast by letting the compiler skip work it has already done. An incremental generator is a pipeline, and the compiler caches the result of every step. When a step returns a value equal to last time’s, everything after it is reused instead of run again.

That only works if the values can be compared. Symbols can’t, because every edit produces new ones, and syntax nodes can’t once their file is edited. That’s why our transform copies the class name, namespace, assembly name and location into a record struct.

Finding the classes matters too. The Roslyn cookbook says ForAttributeWithMetadataName “is at least 99x more efficient than SyntaxProvider.CreateSyntaxProvider“, the general-purpose way to scan syntax.

Combining our classes with CompilationProvider defeats all of this. The compilation changes on every edit, so the combined value is never equal to the previous one, and the output step runs our template again after every keystroke.

Here’s the pipeline many older examples use, and that this article used too. Don’t copy this one. It scans every class with a string compare, and then combines all of them with the whole compilation:

IncrementalValuesProvider<ClassDeclarationSyntax> enumDeclarations = context.SyntaxProvider
  .CreateSyntaxProvider(
      predicate: static (s, _) => IsSyntaxTargetForGeneration(s),
      transform: static (ctx, _) => GetTargetForGeneration(ctx));

IncrementalValueProvider<(Compilation, ImmutableArray<ClassDeclarationSyntax>)> compilationAndEnums
     = context.CompilationProvider.Combine(enumDeclarations.Collect());

context.RegisterSourceOutput(compilationAndEnums,
    (spc, source) => Execute(source.Item1, source.Item2, spc));

The driver can record why each step ran, so we can check this ourselves with a test: run the generator, add an unrelated class to the compilation, run it again, and check that our output step was served from the cache:

[TestMethod]
public void WhenUnrelatedCodeChanges_ThenGeneratedServiceIsCached()
{
    var compilation = Helper.CreateCompilation(PersonModelSource);

    GeneratorDriver driver = CSharpGeneratorDriver.Create(
        [new ServiceGenerator().AsSourceGenerator()],
        driverOptions: new GeneratorDriverOptions(
            IncrementalGeneratorOutputKind.None,
            trackIncrementalGeneratorSteps: true));

    driver = driver.RunGenerators(compilation);

    var edited = compilation.AddSyntaxTrees(
        CSharpSyntaxTree.ParseText("public class Unrelated { }"));

    driver = driver.RunGenerators(edited);

    var reasons = driver.GetRunResult().Results.Single()
        .TrackedOutputSteps
        .SelectMany(step => step.Value)
        .SelectMany(run => run.Outputs)
        .Select(output => output.Reason)
        .ToList();

    Assert.IsNotEmpty(reasons);
    Assert.IsTrue(reasons.All(reason => reason == IncrementalStepRunReason.Cached));
}

With our pipeline the output step reports Cached and the test passes. With the old pipeline above, the same test fails, because its output step reports Modified: the unrelated class changed the compilation, and the template ran again for a class nobody touched.

Generating Using SyntaxFactory

Another approach to generating source code is using SyntaxFactory. It is located at Microsoft.CodeAnalysis.CSharp, and provides a comprehensive set of methods for creating syntax nodes and tokens, giving developers the means to programmatically generate C# code.

We can rewrite the first example:

using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.Text;
using System.Text;

[Generator]
public sealed class ExampleGeneratorSyntaxFactory : IIncrementalGenerator
{
    public void Initialize(IncrementalGeneratorInitializationContext context)
    {
        context.RegisterPostInitializationOutput(ctx =>
        {
            var classBlock = SyntaxFactory.NamespaceDeclaration(SyntaxFactory.ParseName("SourceGeneratorInCSharp"))
                .AddMembers(
                    SyntaxFactory.ClassDeclaration("SyntaxFactoryHelloWorld")
                    .AddModifiers(
                        SyntaxFactory.Token(SyntaxKind.PublicKeyword),
                        SyntaxFactory.Token(SyntaxKind.StaticKeyword)
                    )
                    .AddMembers(
                        SyntaxFactory.MethodDeclaration(
                            SyntaxFactory.ParseTypeName("void"),
                            "SayHello"
                        )
                        .AddModifiers(
                            SyntaxFactory.Token(SyntaxKind.PublicKeyword),
                            SyntaxFactory.Token(SyntaxKind.StaticKeyword)
                        )
                        .AddBodyStatements(
                            SyntaxFactory.ExpressionStatement(
                                SyntaxFactory.InvocationExpression(
                                    SyntaxFactory.MemberAccessExpression(
                                        SyntaxKind.SimpleMemberAccessExpression,
                                        SyntaxFactory.IdentifierName("Console"),
                                        SyntaxFactory.IdentifierName("WriteLine")
                                    ))
                                    .WithArgumentList(
                                        SyntaxFactory.ArgumentList()
                                            .AddArguments(
                                                SyntaxFactory.Argument(
                                                    SyntaxFactory.LiteralExpression(
                                                        SyntaxKind.StringLiteralExpression,
                                                        SyntaxFactory.Literal("Hello From Generator")
                                                    )
                                                )
                                            )
                                    )
                            )
                        )
                    )
                ).NormalizeWhitespace();

            ctx.AddSource("ExampleGeneratorSyntaxFactory.g",
                SourceText.From(classBlock.ToFullString(), Encoding.UTF8));
        });
    }
}

As we can see, a lot of methods need to be used to generate even a simple scenario and we can’t immediately see what the code will look like, without checking the results of the generation.

The Roslyn cookbook goes further and recommends against building generated code from syntax nodes at all. Calling NormalizeWhitespace is expensive, and AddSource wants a string anyway. A template engine like Scriban, or a StringBuilder that tracks indentation, is the better tool.

Emitting Compiler-Generated Files

By default, source generators do not produce artifacts directly. Instead, they generate additional source code during the compilation process, which is compiled along with the rest of the project source code, thus only being viewable through an IDE. This can be a problem, since for this type of file, we can’t do a code review.

To enable persisting source generator files to the file system, we can set the EmitCompilerGeneratedFiles property in our Console project file:

<PropertyGroup>
    <EmitCompilerGeneratedFiles>true</EmitCompilerGeneratedFiles>
</PropertyGroup>

By setting the property alone, the compiler will save the generated files to the disk. And then, we can see that the source-generated files are written to the obj/Debug/net11.0/generated folder. Inside a folder named after the generator’s assembly, each generator gets a folder named after its full type name. The generators printed here have no namespace, so our folders are ExampleGenerator, ExampleGeneratorSyntaxFactory and ServiceGenerator. The trees below come from the sample on GitHub, which keeps the generators in the Generator namespace:

obj/
└── Debug/
    └── net11.0/
        └── generated/
            └── Generator/
                ├── Generator.ExampleGenerator/
                │   └── ExampleGenerator.g.cs
                ├── Generator.ExampleGeneratorSyntaxFactory/
                │   └── ExampleGeneratorSyntaxFactory.g.cs
                └── Generator.ServiceGenerator/
                    ├── GenerateServiceAttribute.g.cs
                    ├── Microsoft.CodeAnalysis.EmbeddedAttribute.cs
                    └── PersonModelService.g.cs

This can be a problem as the bin and obj folders are normally excluded from source control. We can specify the CompilerGeneratedFilesOutputPath property to determine the location of the compiler-emitted files. This property allows us to set a custom path relative to the project root folder:

<PropertyGroup>
    <EmitCompilerGeneratedFiles>true</EmitCompilerGeneratedFiles>
    <CompilerGeneratedFilesOutputPath>Generated</CompilerGeneratedFilesOutputPath>
</PropertyGroup>

This will write the files to the Generated folder in the project:

Generated/
└── Generator/
    ├── Generator.ExampleGenerator/
    │   └── ExampleGenerator.g.cs
    ├── Generator.ExampleGeneratorSyntaxFactory/
    │   └── ExampleGeneratorSyntaxFactory.g.cs
    └── Generator.ServiceGenerator/
        ├── GenerateServiceAttribute.g.cs
        ├── Microsoft.CodeAnalysis.EmbeddedAttribute.cs
        └── PersonModelService.g.cs

Now, when we try to build for a second time after the files have already been written, we get an error:

Error CS0111 Type 'HelloWorld' already defines a member called 'SayHello' with the same parameter types

To resolve this issue, the solution is to remove the emitted files from the project compilation, by using a wildcard pattern to exclude all the .cs files in those folders:

<ItemGroup>
    <!-- Exclude the output of source generators from the compilation -->
    <Compile Remove="$(CompilerGeneratedFilesOutputPath)/**/*.cs" />
</ItemGroup>

With this modification, the output of the source generator is now stored on the disk. This ensures it can be included in source control for easy review during pull requests. Also, and most importantly, it no longer affects the compilation process.

Use Cases

Source generators can be used for some common use cases including:

  • Dependency Injection: We can use source generators to automatically generate code for dependency injection containers, reducing the boilerplate code needed to set up dependencies. They can even replace a runtime IoC/DI container.
  • Data Access Layers: Source generators can help in generating data access, such as entity classes, and repositories based on models or database schema definitions.
  • Builder pattern: Source generators can generate builder classes or fluent interfaces, allowing for more readable and expressive code when constructing complex objects.
  • Code Analysis and Validation: Source generators can check the code they work on during compilation, as our naming rule does. Coding standards in general are a job for analyzers.
  • Automatic Tests Generation: Source generators can assist in automatically generating test cases or test data for unit testing. It saves time in writing repetitive test code.
  • Code Annotations and Documentation: Source generators can create code annotations and inline documentation. This makes it easier for developers to understand and document the purpose and usage of various code elements.

.NET itself ships several. With source-generated regular expressions, the regex engine is written as C# at compile time instead of at runtime, and the options validation generator lets us validate IOptions with a source generator instead of reflection.

We can access a list of implemented source generators in csharp-source-generators GitHub repository.

Conclusion

In this article, we’ve covered the basic concepts of source generators, and through a simple example, we’ve implemented an IIncrementalGenerator.

Using a more complex example, we’ve filtered classes by a marker attribute with ForAttributeWithMetadataName and passed small, equatable models through the pipeline, and we’ve proven with a test that the generator’s output is reused when nothing relevant changes. We’ve also reported diagnostics, and seen how to debug and test the generators.

Regarding the generation of artifacts, we can see that it is possible to add our source codes generated in the source control, thus enabling the code review.

Finally, we describe some use cases for code generators and provide a repository where we can find many of them.

Tested with .NET 11 (SDK 11.0.100, runtime 11.0.0), Microsoft.CodeAnalysis.CSharp 5.9.0, Scriban 7.6.1 and MSTest 4.5.3.