CodeBlanks Logo Icon CodeBlanks

What are source generators?

C# course · Expert · Lesson 37/47

Learn what source generators are and compile-time code generation.

What are source generators?

A source generator is a Roslyn component that runs during compilation and adds new C# code to the compilation. Instead of doing reflection at runtime, it generates the needed code at compile time, which shortens startup.

The generated code is added as additional source files alongside what the student wrote. Generators are commonly used for serialization, dependency injection registration, and DTO generation.

Roslyn and compile time

Source generators are part of the Roslyn compiler platform. The compiler gives the generator the syntax tree and the semantic model; the generator inspects them and emits new code.

This moves runtime cost to compile time. For example, you can find every class marked with an attribute and generate helper methods for each one.

Exercise Generate a class definition

Inside a static class GeneratorDemo, write a method public static string GenerateClass(string typeName). In the body, return $"public class {typeName} {{ }}";. In Main, call Console.WriteLine(GeneratorDemo.GenerateClass("UserDto")).

Show example solution
Console.WriteLine(GeneratorDemo.GenerateClass("UserDto"));
Example solution:
using System;

static class GeneratorDemo
{
    public static string GenerateClass(string typeName)
    {
        return $"public class {typeName} {{ }}";
    }
}

class Program
{
    static void Main()
    {
        Console.WriteLine(GeneratorDemo.GenerateClass("UserDto"));
    }
}

Test yourself

  1. When does a source generator run?

    • At runtime
    • At compile time
    • On shutdown
    • On request
    Show answer

    At compile time — Correct. A source generator runs during compilation.

  2. Match each source generator concept

    Compile time
    Code generation time
    Roslyn
    Compiler platform
    Syntax tree
    Parsed code tree
  3. Complete the GenerateClass method

    public static string ____(string typeName) { return $"public class {typeName} {{ }}"; }
    Show answer
    public static string GenerateClass(string typeName) { return $"public class {typeName} {{ }}"; }

All lessons in Expert