Sitemap

C# Source Generators: Getting Started

4 min readApr 30, 2023

--

Source Generators are a powerful tool that allow developers to automatically generate code during the compilation process. They can help reduce boilerplate code, improve performance, and enable new coding patterns. In this article, we will walk through creating a custom Source Generator to generate code based on specific conditions for a given set of methods.

What is a Source Generator?

A Source Generator is a piece of code that runs during compilation and can inspect your program to produce additional files that are compiled together with the rest of your code.

How do Source Generators work?

During compilation, Source Generators analyze code and metadata and generate additional source code based on those analyses. These are like plugins for the compiler that are executed during compilation.When the compiler loads the Source Generator, it analyzes the code and metadata to identify syntax nodes and semantic information relevant to the Source Generator.

Press enter or click to view image in full size

Source Generator analyzes syntax nodes and generates additional source code based on the analysis. This generated code is added to the compilation as if it were written by the developer. Compilation is complete, and the generated code is included in the assembly.

When to use Source Generators?

Source Generators are ideal for situations where you need to automate repetitive tasks, enforce coding patterns or generate code based on specific conditions in your codebase.Here are some situations where source generators can be particularly useful:

  1. Reducing boilerplate code: If you find yourself writing the same code over and over again, a source generator can automatically generate that code for you. This can save time and reduce the likelihood of errors caused by manual code duplication.
  2. Improving performance: Source generators can generate code that is optimized for specific scenarios, such as data serialization or network communication. This can help improve the performance of the application by reducing the amount of overhead required to perform these operations.
  3. Enabling new coding patterns: Source generators can be used to enable new coding patterns, such as compile-time dependency injection or aspect-oriented programming. This can help developers write more modular, maintainable code that is easier to test and debug.
  4. Adapting to changing requirements: Source generators can be used to adapt code to changing requirements, such as changes to an external API or changes to business logic. This can help reduce the amount of manual code updates required and improve the overall flexibility of the codebase.
  5. Generating code for cross-cutting concerns: Source generators can be used to generate code for cross-cutting concerns, such as logging, error handling, or performance monitoring. This can help ensure that these concerns are addressed consistently across the application and reduce the risk of errors caused by manual coding.

Understanding the Components of a Source Generator

A Source Generator consists of two main components that work together to provide a seamless and efficient code generation process:

Get Meisam Alifallhi’s stories in your inbox

Join Medium for free to get updates from this writer.

the ISyntaxReceiver and the ISourceGenerator. By understanding the components and their relationship, you can create custom Source Generators tailored to your specific requirements.

The ISyntaxReceiver is responsible for collecting and filtering syntax nodes during the compilation process based on specific conditions. The ISourceGenerator is responsible for generating code based on the filtered syntax nodes collected by the ISyntaxReceiver.

These two components work together as follows:

  1. The ISyntaxReceiver collects and filters syntax nodes during the compilation process.
  2. The ISourceGenerator receives the filtered syntax nodes from the ISyntaxReceiver.
  3. The ISourceGenerator generates code based on the filtered syntax nodes.

You can also filter syntax nodes directly in the ISourceGenerator’s Execute method, but using an ISyntaxReceiver is more efficient because it allows you to filter syntax nodes during the compilation process, avoiding unnecessary overhead.

Create a custom Source Generator step-by-step.

  1. Setting up a Source Generator Project
    Create a new Class Library (.NET Standard) project targeting netstandard2.0. To use Source Generators, you need to add the following NuGet packages to your project:
    - Microsoft.CodeAnalysis.CSharp
    - Microsoft.CodeAnalysis.Analyzers
  2. Implementing a Custom Syntax Receiver
 public class CustomSyntaxReceiver : ISyntaxReceiver
{
public List<MethodDeclarationSyntax> CandidateMethods { get; } = new();
public void OnVisitSyntaxNode(SyntaxNode syntaxNode)
{
if (syntaxNode is MethodDeclarationSyntax methodDeclaration &&
methodDeclaration.AttributeLists.Any(al => al.Attributes.Any(a => a.Name.ToString() == "MyCustomAttribute")))
{
CandidateMethods.Add(methodDeclaration);
}
}
}

3. Implementing a Custom Source Generator

 [Generator]
public class CustomSourceGenerator : ISourceGenerator
{
public void Initialize(GeneratorInitializationContext context)
{
context.RegisterForSyntaxNotifications(() => new CustomSyntaxReceiver());
}
//Inside the `Execute` method, retrieve the SyntaxReceiver and generate code based on the filtered methods. Here's a simple example that generates a static class with a method that prints the names of the filtered methods:
public void Execute(GeneratorExecutionContext context)
{
if (context.SyntaxReceiver is not CustomSyntaxReceiver receiver)
return;

var sourceBuilder = new StringBuilder();
sourceBuilder.AppendLine("using System;");
sourceBuilder.AppendLine("namespace GeneratedCode");
sourceBuilder.AppendLine("{");
sourceBuilder.AppendLine(" public static class GeneratedMethodsInfo");
sourceBuilder.AppendLine(" {");
sourceBuilder.AppendLine(" public static void PrintMethodNames()");
sourceBuilder.AppendLine(" {");

foreach (var method in receiver.CandidateMethods)
{
sourceBuilder.AppendLine($" Console.WriteLine(\"{method.Identifier}\");");
}

sourceBuilder.AppendLine(" }");
sourceBuilder.AppendLine(" }");
sourceBuilder.AppendLine("}");

context.AddSource("GeneratedMethodsInfo", sourceBuilder.ToString());
}
}

4. Add the source generator from a project as an analyzer

<!-- replacing paths and names appropriately -->
<ItemGroup>

<ProjectReference Include="path-to-sourcegenerator-project.csproj"
OutputItemType="Analyzer"
ReferenceOutputAssembly="false" />
</ItemGroup>

By implementing a custom ISyntaxReceiver and ISourceGenerator, you can create a powerful and efficient Source Generator that generates code based on specific conditions . Using an ISyntaxReceiver allows you to filter syntax nodes during the compilation process, reducing overhead and improving performance.

In summary, understanding the components of a Source Generator and their relationship is crucial for creating custom Source Generators tailored to your specific requirements. By leveraging the power of ISyntaxReceivers and ISourceGenerators, you can enhance your development process and take full advantage of the benefits offered by Source Generators in C#.

--

--