Home / Forums / How do C# Source Generators work and how can I build one?

UnreliableCode Community

Developer Research, Reverse Engineering & Coding Community

Question

How do C# Source Generators work and how can I build one?

MatrixRecon
3D Math & Vectors
MEMBER
Rep: 225
Join Date: Jan 2025
Posts: 33
Thanks: 55
3y ago · Sep 25, 2022 4:12 PM
#1
I want to write a source generator that scans classes for a custom attribute and automatically generates serialization boilerplate. Where do I start?
MatrixRecon · 3D Mathematics & View Matrix Calculations
The following users thanked MatrixRecon for this post:
VMT_Hooker
VMT / Detours Engineer
VIP
Rep: 310
Join Date: Mar 2023
Posts: 22
Thanks: 80
3y ago · Sep 25, 2022 7:47 PM
#2
Source Generators hook into the Roslyn compiler via ISourceGenerator or IIncrementalGenerator (preferred in modern .NET). IIncrementalGenerator caches syntax node inputs so it only re-generates code when files with your attribute actually change!
VMT_Hooker - Virtual method table swapping made easy
AsmDisasm
x86_64 Disassembler Dev
MEMBER
Rep: 145
Join Date: Feb 2025
Posts: 23
Thanks: 36
3y ago · Sep 27, 2022 1:47 AM
#3
Check out the Microsoft.CodeAnalysis.CSharp NuGet package. Incremental generators are blazingly fast and keep IDE typing responsive.
AsmDisasm · Zydis & Opcode Length Disassembly