JavaRush /Courses /C# SELF /Introduction to Source Generators

Introduction to Source Generators

C# SELF
Level 63, Lesson 3
Available

1. Introduction

When you write code, you've probably caught yourself thinking: "Why do I copy the same code pattern over and over for different classes?" Or: "Why are serialization, logging, data mapping — so many repetitive lines?" Sometimes you'd want someone (or something) to write that tedious pattern for you.

That's where Source Generators come in — a newer capability in C#, introduced in .NET 5 and still evolving. A Source Generator is a library that runs at compile time and can dynamically generate C# code that gets automatically injected into your project before the final build.

Why use them?

  • Routine automation: Gets rid of writing repetitive classes/methods (boilerplate).
  • Compiler-checked safety: Generated code is compiled together with yours (unlike T4 or reflection).
  • High performance: Serialization, DI, mapping, etc. without runtime reflection costs.
  • Support for modern patterns: Enables approaches that were hard/expensive without code generation.

How do Source Generators work "under the hood"?

A Source Generator is a .NET library (usually a Class Library project) implementing the ISourceGenerator interface. During compilation, Roslyn runs all attached generators, giving them access to the syntax tree of your code.

The generator analyzes your code, decides what and where to generate, and creates new C# files which the compiler immediately compiles.

Auto-generating ToString

Let's start simple. Imagine you have a class with many properties and you need to implement ToString. Hand-written it looks like this:

public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
    public override string ToString()
        => $"Person(Name={Name}, Age={Age})";
}

But when the number of properties grows, it's tedious and you can easily forget to update something. A Source Generator can do it for you!

2. How to create your own Source Generator?

Creating the project

Open JetBrains Rider or Visual Studio, create a new project of type Class Library (.NET Standard) — these project types can be generators. Then add NuGet packages:

  • Microsoft.CodeAnalysis.CSharp
  • Microsoft.CodeAnalysis.Analyzers

Important attributes

  • [Generator] — indicates that this class is a Source Generator.

Minimal generator template

Here's a minimal working example:

using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Text;
using System.Text;

[Generator]
public class HelloWorldGenerator : ISourceGenerator
{
    public void Initialize(GeneratorInitializationContext context)
    {
        // You can register additional actions (optional)
    }

    public void Execute(GeneratorExecutionContext context)
    {
        var code = @"
namespace Generated
{
    public static class HelloWorld
    {
        public static string SayHello() => ""Privet, mir! Ya sgenerirovan!"";
    }
}";
        context.AddSource("HelloWorldGenerator", SourceText.From(code, Encoding.UTF8));
    }
}

This simple generator always adds a static class HelloWorld with a method SayHello during compilation.

How to use Source Generators in the main application?

Add the generator project as a NuGet package or a Project Reference in the Analyzer section (see official docs for details).

The generated code is immediately available in your project — no extra includes needed, just use it:

// This will be generated automatically!
using Generated;

Console.WriteLine(HelloWorld.SayHello());

3. Real example: auto-generating ToString

Suppose we want every class marked with the [AutoToString] attribute to automatically get a ToString implementation. For that we'll need to:

  • Create a custom attribute.
  • Analyze all classes with that attribute.
  • Generate a ToString method for each such class.

The attribute

[AttributeUsage(AttributeTargets.Class)]
public class AutoToStringAttribute : Attribute
{
}

Usage in code

[AutoToString]
public class Product
{
    public string Name { get; set; }
    public int Price { get; set; }
}

Simple generation logic

The generator will look for classes with [AutoToString] and generate roughly this code:

public override string ToString() 
    => $"Product(Name={Name}, Price={Price})";

Snippet of actual generator code

The basic idea is to walk the syntax tree with Roslyn:

public void Execute(GeneratorExecutionContext context)
{
    // We analyze all syntax trees
    foreach (var tree in context.Compilation.SyntaxTrees)
    {
        var root = tree.GetRoot();
        // Find all classes with the required attribute (roughly!)
        var classes = root.DescendantNodes()
            .OfType<ClassDeclarationSyntax>()
            .Where(c => c.AttributeLists
                         .SelectMany(al => al.Attributes)
                         .Any(a => a.Name.ToString().Contains("AutoToString")));

        foreach (var @class in classes)
        {
            var className = @class.Identifier.Text;
            // Get all properties of the class
            var props = @class.Members
                .OfType<PropertyDeclarationSyntax>()
                .Select(p => p.Identifier.Text)
                .ToArray();

            var toStringCode = string.Join(", ", props.Select(p => $"{p}={{this.{p}}}"));
            var generated = $@"
partial class {className}
{{
    public override string ToString() => $""{className}({toStringCode})"";
}}";

            context.AddSource($"{className}_ToString", SourceText.From(generated, Encoding.UTF8));
        }
    }
}

Note: for production code you should use a more correct analysis via Roslyn's SemanticModel.

4. Useful nuances

What to watch out for

Source Generators cannot modify existing source files — they can only create new files (for example, additional partial classes, methods, etc.). That means if your class is declared as partial, you can generate additional methods or properties for it.

Sometimes it's tricky to parse syntax correctly and account for language nuances (nested classes, generics, modifiers, etc.). The generator author must ensure generated code is compilable and doesn't "break" the project.

Another pitfall — if you generate methods that implement an interface, make sure files are generated on every build. Otherwise you can get strange compile errors. Modern tools usually handle this, but it's good to keep in mind.

Source Generators vs. reflection

Reflection: runs at runtime, expensive, not compiler-checked, often slow on large data sets.

Source Generator: generates code at compile time. Everything is statically checked, IDE sees methods, autocompletion works, and performance matches regular C# code.

Practical benefits

  • System.Text.Json: generating serialization/deserialization without reflection.
  • Designing DI containers: e.g., Microsoft.Extensions.DependencyInjection with generated dependency graphs.
  • Mappers like Mapster: moving from reflection to compile-time generated mapping code.
  • Test frameworks: auto-generating test methods based on attributes.
  • ASP.NET Minimal APIs (starting with .NET 7): generating endpoint handlers.

Configuration, parameters and options

Generators can be configured via MSBuild parameters, additional files and conventions. You can, for example, generate different ToString depending on the environment (Debug/Release) or app configuration.

How Source Generators relate to real-world tasks

For a developer aiming for clean and fast code, this is a great tool: less routine, more compile-time checks, IDE hints and straightforward refactoring. Knowledge of generators is increasingly asked about in interviews — from serialization and DI to mapping.

Life cycle of a Source Generator

Stage What happens
1. Project is attached Your generator is added as analyzer/reference
2. Roslyn compiles the source The generator receives the AST (abstract syntax tree)
3. Generator runs Adds new .cs files for compilation
4. Everything is compiled Generated files become part of your assembly
5. Code is ready! Generated methods/classes are available to call

5. Debugging and common mistakes

One of the most common newbie mistakes when writing generators is forgetting the partial keyword on the class you want to augment. If you don't mark it partial, the compiler simply won't see your additions. Sometimes the generated file may not appear in the IDE until the first rebuild — don't panic.

Be careful when naming generated files: if you give them all the same name, they'll overwrite each other. Tip: include the class name in the file name you're generating — for example, context.AddSource($"{className}_ToString", ...).

Error from double-importing attributes — if you generate a class with an attribute that already exists in the main project, you'll get a conflict. It's better to move required attributes to a common project or generate the attribute only when needed.

2
Task
C# SELF, level 63, lesson 3
Locked
Automatic ToString Method Generation
Automatic ToString Method Generation
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION