C#
IIncrementalGenerator
Learn to write incremental source generators with IIncrementalGenerator.
IIncrementalGenerator
IIncrementalGenerator is a modern, cacheable generator interface. It replaces the older ISourceGenerator; instead of rescanning the whole syntax tree on every compile, it re-runs only the parts that changed.
You build a pipeline: each step transforms an input and the result is cached. This significantly cuts build time on large projects.
Incremental pipeline design
In an incremental generator, each step returns an IncrementalValueProvider or IncrementalValuesProvider. You filter with Where, transform with Select, and gather with Collect.
Each step is cached; if the input is unchanged, the step does not re-run. This requires pure functions: the same input must always produce the same output.
Exercise Filter and generate DTOs
Add a method public static List<string> FilterAndGenerate(IEnumerable<string> typeNames) to the static class IncrementalDemo. In the body, return typeNames.Where(name => name.EndsWith("Dto")).Select(name => $"public class {name} {{ }}").ToList(). In Main, pass new[] { "UserDto", "Account", "OrderDto" } and print each result.
Show example solution
foreach (var g in IncrementalDemo.FilterAndGenerate(new[] { "UserDto", "Account", "OrderDto" })) Console.WriteLine(g);
Example solution:
using System;
using System.Collections.Generic;
using System.Linq;
static class IncrementalDemo
{
public static List<string> FilterAndGenerate(IEnumerable<string> typeNames)
{
return typeNames
.Where(name => name.EndsWith("Dto"))
.Select(name => $"public class {name} {{ }}")
.ToList();
}
}
class Program
{
static void Main()
{
foreach (var g in IncrementalDemo.FilterAndGenerate(new[] { "UserDto", "Account", "OrderDto" }))
{
Console.WriteLine(g);
}
}
}
Test yourself
-
Complete the pipeline step
names.Where(name => name.EndsWith("Dto")).____(name => $"public class {name} {{ }}").ToList();
Show answer
names.Where(name => name.EndsWith("Dto")).Select(name => $"public class {name} {{ }}").ToList();
-
What is the main benefit of IIncrementalGenerator?
- Less code to write
- Runtime reflection
- Shorter file names
- Faster builds through caching
Show answer
Faster builds through caching — Correct. The incremental design enables faster builds via caching.
-
Match each pipeline method
- Where
- Filter items
- Select
- Transform each item
- Collect
- Gather results
Next lesson: Generator attribute