SlideShare a Scribd company logo
C# metaprogramming con i Source Generator
Alessandro Melchiori - @amelchiori
CodicePlastico
Roslyn History
2010
Hiring for Rolsyn
Roslyn History
2010
Hiring for Rolsyn
2011
V1 released
Roslyn History
2010
Hiring for Rolsyn
2011
V1 released
2020
C# Source Gen
Roslyn History
2010
Hiring for Rolsyn
2011
V1 released
2012
Un compilatore
per amico
2020
C# Source Gen
What exactly are source generator?
● New metaprogramming technology
● Part of compilation process
● Can access a model of our code
● Generated output are new files
What problems are solved by source generator?
● Generating boilerplate code
○ Standard implementation of Equals, GetHashCode, ==, ToString
○ Type generation from schemas such as xsd
○ Object mapping
○ Code for object materialization
● Performance optimization
○ Serialization without reflection
○ Register types for DI without reflection
How does it work?
High level design goals of source generators
Generators produce one or
more strings that represent
C# source code to be added
to the compilation.
High level design goals of source generators
Generators produce one or
more strings that represent
C# source code to be added
to the compilation.
Explicitly additive only.
Generators can add new source
code to a compilation but may not
modify existing user code.
High level design goals of source generators
Generators produce one or
more strings that represent
C# source code to be added
to the compilation.
Explicitly additive only.
Generators can add new source
code to a compilation but may not
modify existing user code.
May access additional
files, that is, non-C#
source texts.
High level design goals of source generators
Run un-ordered, each
generator will see the same
input compilation, with no
access to files created by
other source generators.
High level design goals of source generators
Run un-ordered, each
generator will see the same
input compilation, with no
access to files created by
other source generators.
A user specifies the
generators to run via list of
assemblies, much like
analyzers.
High level design goals of source generators
Run un-ordered, each
generator will see the same
input compilation, with no
access to files created by
other source generators.
A user specifies the
generators to run via list of
assemblies, much like
analyzers.
Generators create a pipeline,
starting from base input sources
and mapping them to the output
they wish to produce.
Implementing a source generator
namespace Microsoft.CodeAnalysis
{
public interface IIncrementalGenerator
{
void Initialize(IncrementalGeneratorInitializationContext context);
}
}
Implementing a source generator
[Generator]
public class MyGenerator : IIncrementalGenerator
{
public void Initialize(IncrementalGeneratorInitializationContext context)
{
// define the execution pipeline here via a series of transformations
}
}
DEMO
Pipeline based execution
The defined transformations
are not executed directly at
initialization, and instead are
deferred until the data they
are using changes.
Pipeline based execution
The defined transformations
are not executed directly at
initialization, and instead are
deferred until the data they
are using changes.
These transformations are
used to form a directed
graph of actions that can be
executed on demand later, as
the input data changes.
Pipeline based execution
The defined transformations
are not executed directly at
initialization, and instead are
deferred until the data they
are using changes.
These transformations are
used to form a directed
graph of actions that can be
executed on demand later, as
the input data changes.
Between each transformation,
the data produced is cached,
allowing previously calculated
values to be re-used where
applicable.
Outputting values
RegisterSourceOutput
Allows a generator author to produce source files and diagnostics that will be included in the users compilation.
RegisterImplementationSourceOutput
Works in the same way as RegisterSourceOutput but declares that the source produced has no semantic
impact on user code from the point of view of code analysis.
RegisterPostInitializationOutput
Allows a generator author to provide source code immediately after initialization has run.
Handling cancelation
Caching
DEMO
Pipeline best practices
Extract out information early
It is best to get the information out of the
inputs as early as possible in the pipeline.
This ensures the host is not caching large,
expensive object such as symbols.
Pipeline best practices
Extract out information early
It is best to get the information out of the
inputs as early as possible in the pipeline.
This ensures the host is not caching large,
expensive object such as symbols.
Use value types where possible
Value types are more amenable to caching and
usually have well defined and easy to understand
comparison semantics.
Pipeline best practices
Extract out information early
It is best to get the information out of the
inputs as early as possible in the pipeline.
This ensures the host is not caching large,
expensive object such as symbols.
Use value types where possible
Value types are more amenable to caching and
usually have well defined and easy to understand
comparison semantics.
Use multiple Transformations:
The more transformations you break the
operations into, the more opportunities there
are to cache. Think of transformations as
being 'check points' in the execution graph.
The more check points the more chances
there are to match a cached value and skip
any remaining work.
Pipeline best practices
Build a data model
Rather than trying to pass each input item into a Register...Output method,
consider building a data model to be the final item passed to the output. Use the
transformations to manipulate the data model, and have well defined equality that
allows you to correctly compare between revisions of the model. This also makes
testing the final Register...Outputs significantly simpler: you can just call the
method with a dummy data model and check the generated code, rather than
trying to emulate the incremental transformations.
Pipeline best practices
Build a data model
Rather than trying to pass each input item into a Register...Output method,
consider building a data model to be the final item passed to the output. Use the
transformations to manipulate the data model, and have well defined equality that
allows you to correctly compare between revisions of the model. This also makes
testing the final Register...Outputs significantly simpler: you can just call the
method with a dummy data model and check the generated code, rather than
trying to emulate the incremental transformations.
Consider the order of combines
Ensure that you are only combining the minimal
amount of information needed (this comes back to
'Extract out information early').
ALESSANDRO MELCHIORI
Founder & Software developer @ CodicePlastico
alessandro@codiceplastico.com
@amelchiori
FOLLOW US
Grazie!

More Related Content

PDF
NetWork - 15.10.2011 - Applied code generation in .NET
PDF
PDF
M azhar
PDF
Software Engineering Tools and Practices.pdf
PPT
CASE tools and their effects on software quality
PDF
ABSE and AtomWeaver : A Quantum Leap in Software Development
PPT
Parasoft .TEST, Write better C# Code Using Data Flow Analysis
PPTX
"Mastering Source Generators", Vladislav Antonyuk.pptx
NetWork - 15.10.2011 - Applied code generation in .NET
M azhar
Software Engineering Tools and Practices.pdf
CASE tools and their effects on software quality
ABSE and AtomWeaver : A Quantum Leap in Software Development
Parasoft .TEST, Write better C# Code Using Data Flow Analysis
"Mastering Source Generators", Vladislav Antonyuk.pptx

Similar to C# metaprogramming with source generator.pdf (20)

PDF
Uml examples
PDF
Software Analytics: Data Analytics for Software Engineering
PDF
Mainframes agile2012
DOCX
New folderIMAG2318.jpgNew folderIMAG2319.jpgNew folder.docx
PDF
Generator
PDF
SUBJECT
PPTX
PDF
Software Engineering : OOAD using UML
PPTX
Lesson 1 - System Development LifeCycles_48b8340c0dd570b721da1199655b765e.pptx
PPTX
SAD07 - Project Management
PPTX
Discrete Event Simulation, CASE tool built using C#
DOC
Session3
PPTX
Interaction modelling is further classified into two types: Use case diagram....
DOCX
Incremental model
PPT
Rhapsody Software
PPTX
01_IT4557.pptx
PPT
PPTX
Agile MDD
PDF
SE_chap1.pdf
PDF
Continuous Delivery Overview
Uml examples
Software Analytics: Data Analytics for Software Engineering
Mainframes agile2012
New folderIMAG2318.jpgNew folderIMAG2319.jpgNew folder.docx
Generator
SUBJECT
Software Engineering : OOAD using UML
Lesson 1 - System Development LifeCycles_48b8340c0dd570b721da1199655b765e.pptx
SAD07 - Project Management
Discrete Event Simulation, CASE tool built using C#
Session3
Interaction modelling is further classified into two types: Use case diagram....
Incremental model
Rhapsody Software
01_IT4557.pptx
Agile MDD
SE_chap1.pdf
Continuous Delivery Overview
Ad

More from Alessandro Melchiori (20)

PDF
Scale your (aks) cluster, luke!
PDF
A quick introduction to AKS
PDF
Developing reliable applications with .net core and AKS
PDF
VS Code tools for docker
PPTX
Developing reliable applications with .net core and AKS
PDF
How to search...better! (azure search)
PDF
AKS: k8s e azure
PDF
How to search...better!
PPTX
A quick tour around Azure Dev Spaces
PPTX
Azure functions: from a function to a whole application in 60 minutes
PPTX
Aks: k8s e azure
PDF
Monitoring docker: from zero to Azure
PPTX
Cooking Akka.net and Azure Service Fabric together
PPTX
Azure data platform overview
PPTX
ACR + ACS + VSTS: a complete ALM pipeline with docker and azure
PPTX
Docker & Azure
PDF
Docker and Azure
PPTX
Come ti "pusho" il web con WebSockets: da 0 a SignalR
PPTX
Docker & azure
PPTX
Azure service fabric: a gentle introduction
Scale your (aks) cluster, luke!
A quick introduction to AKS
Developing reliable applications with .net core and AKS
VS Code tools for docker
Developing reliable applications with .net core and AKS
How to search...better! (azure search)
AKS: k8s e azure
How to search...better!
A quick tour around Azure Dev Spaces
Azure functions: from a function to a whole application in 60 minutes
Aks: k8s e azure
Monitoring docker: from zero to Azure
Cooking Akka.net and Azure Service Fabric together
Azure data platform overview
ACR + ACS + VSTS: a complete ALM pipeline with docker and azure
Docker & Azure
Docker and Azure
Come ti "pusho" il web con WebSockets: da 0 a SignalR
Docker & azure
Azure service fabric: a gentle introduction
Ad

Recently uploaded (20)

PDF
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PPTX
Big Data Technologies - Introduction.pptx
PPTX
Programs and apps: productivity, graphics, security and other tools
PDF
Unlocking AI with Model Context Protocol (MCP)
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PPT
Teaching material agriculture food technology
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PPTX
MYSQL Presentation for SQL database connectivity
PDF
Machine learning based COVID-19 study performance prediction
PDF
Electronic commerce courselecture one. Pdf
PPTX
Understanding_Digital_Forensics_Presentation.pptx
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PDF
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
PDF
Spectral efficient network and resource selection model in 5G networks
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
Dropbox Q2 2025 Financial Results & Investor Presentation
Big Data Technologies - Introduction.pptx
Programs and apps: productivity, graphics, security and other tools
Unlocking AI with Model Context Protocol (MCP)
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
The Rise and Fall of 3GPP – Time for a Sabbatical?
Reach Out and Touch Someone: Haptics and Empathic Computing
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
Teaching material agriculture food technology
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
Diabetes mellitus diagnosis method based random forest with bat algorithm
MYSQL Presentation for SQL database connectivity
Machine learning based COVID-19 study performance prediction
Electronic commerce courselecture one. Pdf
Understanding_Digital_Forensics_Presentation.pptx
“AI and Expert System Decision Support & Business Intelligence Systems”
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
Spectral efficient network and resource selection model in 5G networks

C# metaprogramming with source generator.pdf

  • 1. C# metaprogramming con i Source Generator Alessandro Melchiori - @amelchiori CodicePlastico
  • 3. Roslyn History 2010 Hiring for Rolsyn 2011 V1 released
  • 4. Roslyn History 2010 Hiring for Rolsyn 2011 V1 released 2020 C# Source Gen
  • 5. Roslyn History 2010 Hiring for Rolsyn 2011 V1 released 2012 Un compilatore per amico 2020 C# Source Gen
  • 6. What exactly are source generator? ● New metaprogramming technology ● Part of compilation process ● Can access a model of our code ● Generated output are new files
  • 7. What problems are solved by source generator? ● Generating boilerplate code ○ Standard implementation of Equals, GetHashCode, ==, ToString ○ Type generation from schemas such as xsd ○ Object mapping ○ Code for object materialization ● Performance optimization ○ Serialization without reflection ○ Register types for DI without reflection
  • 8. How does it work?
  • 9. High level design goals of source generators Generators produce one or more strings that represent C# source code to be added to the compilation.
  • 10. High level design goals of source generators Generators produce one or more strings that represent C# source code to be added to the compilation. Explicitly additive only. Generators can add new source code to a compilation but may not modify existing user code.
  • 11. High level design goals of source generators Generators produce one or more strings that represent C# source code to be added to the compilation. Explicitly additive only. Generators can add new source code to a compilation but may not modify existing user code. May access additional files, that is, non-C# source texts.
  • 12. High level design goals of source generators Run un-ordered, each generator will see the same input compilation, with no access to files created by other source generators.
  • 13. High level design goals of source generators Run un-ordered, each generator will see the same input compilation, with no access to files created by other source generators. A user specifies the generators to run via list of assemblies, much like analyzers.
  • 14. High level design goals of source generators Run un-ordered, each generator will see the same input compilation, with no access to files created by other source generators. A user specifies the generators to run via list of assemblies, much like analyzers. Generators create a pipeline, starting from base input sources and mapping them to the output they wish to produce.
  • 15. Implementing a source generator namespace Microsoft.CodeAnalysis { public interface IIncrementalGenerator { void Initialize(IncrementalGeneratorInitializationContext context); } }
  • 16. Implementing a source generator [Generator] public class MyGenerator : IIncrementalGenerator { public void Initialize(IncrementalGeneratorInitializationContext context) { // define the execution pipeline here via a series of transformations } }
  • 17. DEMO
  • 18. Pipeline based execution The defined transformations are not executed directly at initialization, and instead are deferred until the data they are using changes.
  • 19. Pipeline based execution The defined transformations are not executed directly at initialization, and instead are deferred until the data they are using changes. These transformations are used to form a directed graph of actions that can be executed on demand later, as the input data changes.
  • 20. Pipeline based execution The defined transformations are not executed directly at initialization, and instead are deferred until the data they are using changes. These transformations are used to form a directed graph of actions that can be executed on demand later, as the input data changes. Between each transformation, the data produced is cached, allowing previously calculated values to be re-used where applicable.
  • 21. Outputting values RegisterSourceOutput Allows a generator author to produce source files and diagnostics that will be included in the users compilation. RegisterImplementationSourceOutput Works in the same way as RegisterSourceOutput but declares that the source produced has no semantic impact on user code from the point of view of code analysis. RegisterPostInitializationOutput Allows a generator author to provide source code immediately after initialization has run.
  • 24. DEMO
  • 25. Pipeline best practices Extract out information early It is best to get the information out of the inputs as early as possible in the pipeline. This ensures the host is not caching large, expensive object such as symbols.
  • 26. Pipeline best practices Extract out information early It is best to get the information out of the inputs as early as possible in the pipeline. This ensures the host is not caching large, expensive object such as symbols. Use value types where possible Value types are more amenable to caching and usually have well defined and easy to understand comparison semantics.
  • 27. Pipeline best practices Extract out information early It is best to get the information out of the inputs as early as possible in the pipeline. This ensures the host is not caching large, expensive object such as symbols. Use value types where possible Value types are more amenable to caching and usually have well defined and easy to understand comparison semantics. Use multiple Transformations: The more transformations you break the operations into, the more opportunities there are to cache. Think of transformations as being 'check points' in the execution graph. The more check points the more chances there are to match a cached value and skip any remaining work.
  • 28. Pipeline best practices Build a data model Rather than trying to pass each input item into a Register...Output method, consider building a data model to be the final item passed to the output. Use the transformations to manipulate the data model, and have well defined equality that allows you to correctly compare between revisions of the model. This also makes testing the final Register...Outputs significantly simpler: you can just call the method with a dummy data model and check the generated code, rather than trying to emulate the incremental transformations.
  • 29. Pipeline best practices Build a data model Rather than trying to pass each input item into a Register...Output method, consider building a data model to be the final item passed to the output. Use the transformations to manipulate the data model, and have well defined equality that allows you to correctly compare between revisions of the model. This also makes testing the final Register...Outputs significantly simpler: you can just call the method with a dummy data model and check the generated code, rather than trying to emulate the incremental transformations. Consider the order of combines Ensure that you are only combining the minimal amount of information needed (this comes back to 'Extract out information early').
  • 30. ALESSANDRO MELCHIORI Founder & Software developer @ CodicePlastico alessandro@codiceplastico.com @amelchiori