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

UnreliableCode Community

Developer Research, Reverse Engineering & Coding Community

Question

How do C# Source Generators work and how can I build one? [Discussion #7]

ReflectPro
Reflection & Roslyn
MEMBER
Rep: 355
Join Date: Mar 2022
Posts: 9
Thanks: 75
4y ago · Mar 25, 2022 12:06 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?
ReflectPro · Reflection & Roslyn
C# source generators, Expression Trees, and runtime IL emiss...
The following users thanked ReflectPro for this post:
LinQ_Lover
C# Developer
MEMBER
Rep: 313
Join Date: Jul 2020
Posts: 8
Thanks: 27
4y ago · Mar 25, 2022 3:27 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!
LinQ_Lover · C# Developer
Clean code, fluent LINQ expressions, and expressive C# patte...
PInvokeMaster
Interoperability Specialist
VIP
Rep: 247
Join Date: Feb 2021
Posts: 6
Thanks: 83
4y ago · Mar 25, 2022 6:27 PM
#3
Check out the Microsoft.CodeAnalysis.CSharp NuGet package. Incremental generators are blazingly fast and keep IDE typing responsive.
PInvokeMaster · Interoperability Specialist
P/Invoke, NativeAOT, C# to C++ native interoperability, and ...