C# 9 Source Generators: Removing Reflection

On this page

Reflection is slow. It happens at runtime, bypasses type safety, and prevents trimming. Source Generators solve this by generating code at compile time. In this guide, we build a generator that automatically implements a `MapTo` method for DTOs, replacing AutoMapper.

The Goal

C#14 lines
[AutoMap(typeof(UserEntity))]
public partial class UserDto
{
    public string Username { get; set; }
}

// Generated Code should look like:
partial class UserDto
{
    public void MapFrom(UserEntity entity)
    {
        this.Username = entity.Username;
    }
}

The Generator Logic

C#14 lines
[Generator]
public class MapperGenerator : ISourceGenerator
{
    public void Execute(GeneratorExecutionContext context)
    {
        var syntaxReceiver = (MySyntaxReceiver)context.SyntaxReceiver;
        foreach (var classDecl in syntaxReceiver.CandidateClasses)
        {
            // Analyze properties using Roslyn Semantic Model
            // Generate StringBuilder content
            context.AddSource($"{className}_Map.g.cs", sourceText);
        }
    }
}

Key Takeaways

  • Source Generators enable **Zero-Overhead abstractions**.
  • They are essential for **Native AOT** compatibility.
  • Debug them by setting `<IsRoslynComponent>true</IsRoslynComponent>`.

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

Subscribe to get the latest posts sent to your email.

Written by

Nithin Mohan TK

Hello Namaste! 👋🏻 I'm an accomplished Enterprise Solution Architect & Engineering Leader with 20+ years of progressive experience architecting, building, and scaling transformative enterprise solutions. ⚜️ Solution Architect / AI & Cloud 📌 Galway, Ireland

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.