Lesson 16 of 40
Advanced C#
Expert
60 min
Source Generators & Roslyn
Write Roslyn source generators to eliminate boilerplate at compile time — from simple attribute processors to full incremental generators.
Part 1: Incremental Source Generators
[Generator]
public class MyGenerator : IIncrementalGenerator
{
public void Initialize(IncrementalGeneratorInitializationContext ctx)
{
var pipeline = ctx.SyntaxProvider
.CreateSyntaxProvider(Predicate, Transform);
ctx.RegisterSourceOutput(pipeline, Emit);
}
}
public class MyGenerator : IIncrementalGenerator
{
public void Initialize(IncrementalGeneratorInitializationContext ctx)
{
var pipeline = ctx.SyntaxProvider
.CreateSyntaxProvider(Predicate, Transform);
ctx.RegisterSourceOutput(pipeline, Emit);
}
}
Part 2: Debugging Source Generators
Add this to your generator project to attach VS debugger:
#if DEBUG
System.Diagnostics.Debugger.Launch();
#endif
VS 2026 also supports attaching directly to the compiler host via Debug → Attach to Process → VBCSCompiler.System.Diagnostics.Debugger.Launch();
#endif
Part 3: Real-World Use Cases
Source generators power frameworks like:
- System.Text.Json — context-based serialization without reflection
- Entity Framework Core — compiled models
- MediatR — request handler registration
- MAUI — XAML to C# compilation
Part 4: Unit Testing Generators
var driver = CSharpGeneratorDriver.Create(new MyGenerator());
driver = driver.RunGenerators(compilation);
var result = driver.GetRunResult();
Assert.Single(result.GeneratedTrees);
// Verify generated code matches expected
driver = driver.RunGenerators(compilation);
var result = driver.GetRunResult();
Assert.Single(result.GeneratedTrees);
// Verify generated code matches expected