Source Generators in C# 9: Compile-Time Code Generation

Metaprogramming in C# has historically relied on reflection (slow at runtime) or T4 templates (clunky build integration). C# 9 changes the game with Source Generators. They allow you to hook into the compilation process, inspect your code, and generate new C# files on the fly that get compiled with your project.

How It Works

flowchart LR
    SourceCode[Your C# Code] --> Compiler[Roslyn Compiler]
    Compiler --> Analysis[Analysis Phase]
    Analysis --> Generator[Source Generator]
    Generator --> NewSource[New C# Source]
    NewSource --> Compiler
    Compiler --> Output[DLL / Exe]
    
    style Generator fill:#FFF3E0,stroke:#E65100,stroke-width:2px
    style NewSource fill:#E8F5E9,stroke:#2E7D32

Example: Auto-Implementing INotifyPropertyChanged

Building view models often involves repetitive boilerplate code. A source generator can automate this.

// What you write
public partial class UserViewModel
{
    [AutoNotify]
    private string _name;
}

// What the Generator creates (in memory/intermediate folder)
public partial class UserViewModel : INotifyPropertyChanged
{
    public string Name
    {
        get => _name;
        set
        {
            if (_name != value)
            {
                _name = value;
                PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Name)));
            }
        }
    }
    public event PropertyChangedEventHandler PropertyChanged;
}

Why Is This Better?

  • Performance: No runtime reflection. It’s just fast, static code.
  • Debugging: You can debug generated code just like your own.
  • IntelliSense: Generated properties show up in your IDE instantly.

Getting Started

To create a generator, you implement the ISourceGenerator interface and tag your class with [Generator]. You’ll need to reference the Microsoft.CodeAnalysis.CSharp packages.

References


Discover more from C4: Container, Code, Cloud & Context

Subscribe to get the latest posts sent to your email.

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.