Roslyn `IIncrementalGenerator` Pipeline Architecture
1Concept
`IIncrementalGenerator` hooks into the Roslyn compiler compilation pipeline. It inspects syntax trees, filters symbols incrementally, and outputs C# source files that are compiled directly into the target assembly.
2Architecture Diagram
[ User Code with Attributes ]
│
▼
[ Roslyn SyntaxProvider / Incremental Generator ]
│ (Caches intermediate model: only re-runs when annotated code edits occur)
▼
[ Emits Generated .g.cs Files ] ──> Merged into final compilation with ZERO runtime reflection!3Code Example
C# 13 & .NET 9
using System;
// Conceptual demonstration of Source Generated output
public partial class UserDto
{
public int Id { get; set; }
public string Name { get; set; } = string.Empty;
}
// In real applications, the Source Generator emits this partial class automatically:
public partial class UserDto
{
public string ToCustomJsonString() => $"{{\"id\":{Id},\"name\":\"{Name}\"}}";
}
public class SourceGeneratorConceptDemo
{
public static void Main()
{
var user = new UserDto { Id = 101, Name = "Alice" };
Console.WriteLine($"Generated Output: {user.ToCustomJsonString()}");
}
}4Expected Output
Generated Output: {"id":101,"name":"Alice"}5Key Takeaways
- ✓Incremental generators cache steps to maintain sub-second IDE typing performance.
- ✓Replaces slow runtime reflection with compile-time generated strongly-typed code.
- ✓Guarantees 100% Native AOT compatibility.