Using C# Source Generators for Code Generation
Jul 04, 2025 am 01:10 AMUsing Source Generators in C# projects improves performance, reduces reflections, and optimizes the development experience by generating code during compilation. Specific methods include: 1. Create a class library project and reference the necessary NuGet package; 2. Implement the ISourceGenerator interface and override the Initialize and Execute methods; 3. Check the class with a specific Attribute in Execute and generate code. Common uses include attribute notification, serialization support, dependency injection registration, and constant generation. Debugging skills include outputting logs, attaching compilation processes, and writing unit test verification generation code. Be careful to avoid complex logic affecting the construction speed and select appropriate technologies such as reflection or IL Weaving based on the scene.
Using Source Generators in C# projects to generate code can improve performance, reduce the use of runtime reflections, and make the code cleaner. Compared with traditional code generation methods (such as T4 templates or runtime dynamic generation), Source Generators are executed during the compile period, will not affect the operation efficiency, and can integrate better with the IDE.

How to get started with Source Generators
To create a Source Generator, you first need to create a .NET Standard or .NET Core class library project and reference the two NuGet packages, Microsoft.CodeAnalysis.CSharp
and Microsoft.CodeAnalysis.Analyzers
.

Then, you need to implement the ISourceGenerator
interface and override the Initialize
and Execute
methods in it. The former is used to register some listening actions, while the latter is where the code is actually generated.
For example: You can check whether the class in the program has a custom Attribute in the Execute
method, and then generate the corresponding auxiliary class based on this information.

[Generator] public class MySourceGenerator: ISourceGenerator { public void Initialize(GeneratorInitializationContext context) { // Register syntax receiver context.RegisterForSyntaxNotifications(() => new SyntaxReceiver()); } public void Execute(GeneratorExecutionContext context) { if (context.SyntaxContextReceiver is not SyntaxReceiver receiver) return; foreach (var candidateClass in receiver.CandidateClasses) { var className = candidateClass.Identifier.Text; var source = $@"namespace GeneratedCode {{ public partial class {className} {{ public void GeneratedMethod() {{ System.Console.WriteLine(""Hello from generated code!""); }} }} }}"; context.AddSource($"{className}.g.cs", source); } } }
Common uses and applicable scenarios
Source Generators can be used to do many things, and here are some common uses:
- Property notification : For example, the implementation of
INotifyPropertyChanged
is automatically generated in MVVM mode. - Serialization support : Automatically generate serialization/deserialization code for certain types to avoid runtime reflection.
- Dependency injection registration : Scan the class of a specific tag and automatically generates the registration code.
- Constant generation : Read data from external files and generate strongly typed constant classes at compile time.
All of these usages can significantly reduce runtime overhead while keeping the development experience friendly.
If you are maintaining an SDK or framework, Source Generators is a very good choice, which allows you to provide "looks automatic" functionality, and is actually done during the compilation phase.
Debugging and testing skills
Debugging Source Generators is a bit challenging because it runs during compilation. Here are some practical tips:
- Use
Console.WriteLine()
to output the log to the output window (see in Visual Studio). - Create a test project, reference your Source Generator and observe the generated code.
- Attach to the compilation process (usually
VBCSCompiler.exe
) for debugging in Visual Studio. - Use Roslyn's test SDK to write unit tests to verify that the generated code is in line with expectations.
Also, be careful not to do too much complex logic in Source Generator. Because it is part of the compilation, if it is too slow, it will affect the build speed.
Some last things to note
Although Source Generators are powerful, they are not omnipotent. Some situations are more suitable for handling with runtime reflection or AOP tools. For example:
- Reflection may be easier if you are not sensitive to performance.
- If you want to modify the existing code structure instead of generating new code, it may be more suitable to use the IL Weaving tool.
- Pay attention to version compatibility. Different versions of the .NET SDK support for Source Generators is slightly different.
Basically that's it. After mastering Source Generators, you will find that many things that were previously handled by runtime can now be handled in the compilation stage. Not only does it perform well, but it is also easier to maintain.
The above is the detailed content of Using C# Source Generators for Code Generation. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

The authors of a new paper propose a way to "enhance" code generation. Code generation is an increasingly important capability in artificial intelligence. It automatically generates computer code based on natural language descriptions by training machine learning models. This technology has broad application prospects and can transform software specifications into usable code, automate back-end development, and assist human programmers to improve work efficiency. However, generating high-quality code remains challenging for AI systems, compared with language tasks such as translation or summarization. The code must accurately conform to the syntax of the target programming language, handle edge cases and unexpected inputs gracefully, and handle the many small details of the problem description accurately. Even small bugs that may seem innocuous in other areas can completely disrupt the functionality of a program, causing

How to use the Hyperf framework for code generation 1. Introduction The Hyperf framework is a high-performance microservice framework based on Swoole2.0+. It has a built-in code generator based on the Hyperf framework, which can help us quickly generate common code files and improve development efficiency. This article will introduce how to use the code generation function of the Hyperf framework, including the generation of controllers, models, and validators. 2. Installation and configuration To install the Hyperf framework, first, we need to install Hyp through Composer

Generate code for the inventory counting function in the PHP inventory management system. In modern enterprises, inventory is a very important resource. Accurately managing inventory is critical to the smooth operation of your business. In order to better manage inventory, many companies use inventory management systems to track inventory changes and update inventory records in real time. Among them, the inventory counting function is an important part of the inventory management system. This article will introduce you to how to use PHP to write the inventory counting function in the inventory management system and provide code examples. First, we need to understand

Python metaprogramming basics Python metaprogramming is the ability to dynamically manipulate Python code, which makes Python a very powerful language. Metaprogramming can be implemented in the following ways: Class decorator: A class decorator is a decorator that modifies the definition of a class. It can be used to add or modify the properties and methods of a class, and can also be used to control the instantiation process of a class. defadd_method_to_class(cls):defnew_method(self):print("Thisisanewmethod")setattr(cls,"new_method",new_method)returncls@a

Reflection is very useful in metaprogramming and code generation in the Go language: Metaprogramming: allows the program to create new types, functions, and variables at runtime, and modify existing type structures. Code generation: Code snippets can be generated dynamically and executed at runtime, such as generating functions that implement a specific interface.

Generate code for the inventory count planning function in the PHP inventory management system. As an important enterprise management tool, the inventory management system can help enterprises achieve effective management, control and optimization of inventory. In the inventory management system, the inventory count plan is a very important function. It can help enterprises understand the inventory situation in real time, predict inventory changes, and take corresponding adjustment measures in a timely manner. In PHP, we implement the inventory count planning function by writing code. The following will introduce how to generate inventory disks through PHP code.

How to handle automatic generation of form data and code generation in Java? Overview: In Java development, processing form data is a very common task. Normally, we need to manually write code to handle the generation and submission of form data. However, in the actual development process, writing code manually can be very tedious and error-prone. In order to improve development efficiency, we can use some tools and frameworks to automatically generate and process form data. This article will introduce how to use Thymeleaf and Spr in Java

Code generation in the Go language is a technology that uses templates to create new code, which can improve development efficiency, generate consistent code, and improve code quality. Use the text/template library to define templates containing static text and dynamic data to create code generators that generate error handling code. Based on a template, this code generator parses existing code to create a new error handler, including ID and description fields, and generates the appropriate error message. It helps automatically generate consistent error handling code, improving code maintainability and readability.
