🏠 VisualStudioTutor.com  ·  C# Tutorial Home  ·  C# Lesson 32 of 40
Lesson 32 of 40 Metaprogramming Expert ⏱ 35 min

Source Generators & Roslyn APIs

Generate C# source code during compilation with Roslyn so repetitive code can be produced automatically without reflection at runtime.

Part 1: What You Will Learn

Generate C# source code during compilation with Roslyn so repetitive code can be produced automatically without reflection at runtime.

  • Create a separate analyzer/source-generator project.
  • Implement `IIncrementalGenerator`.
  • Add generated source during compilation.
  • Reference the generator as an analyzer from a consuming project.

Project setup: Create a class library for the generator, add the `Microsoft.CodeAnalysis.CSharp` package, and reference the generator from your app as an analyzer. A generator project commonly targets a compatible target such as netstandard2.0.

Part 2: Topic-Specific Working Example

The following example is written specifically for this lesson. Create the project described above, enter the code, run it, and then change some values to observe how the feature behaves.

using Microsoft.CodeAnalysis;

[Generator]
public sealed class GreetingGenerator : IIncrementalGenerator
{
    public void Initialize(
        IncrementalGeneratorInitializationContext context)
    {
        context.RegisterPostInitializationOutput(output =>
        {
            output.AddSource(
                "GeneratedGreeting.g.cs",
                """
                namespace GeneratedCode;

                public static class GeneratedGreeting
                {
                    public static string GetMessage()
                        => "Hello from generated C# code!";
                }
                """);
        });
    }
}

// In the consuming application:
// using GeneratedCode;
// Console.WriteLine(GeneratedGreeting.GetMessage());

Part 3: How the Code Works

  • The generator runs as part of compilation; the generated class becomes part of the consuming compilation.
  • `RegisterPostInitializationOutput` is suitable for source that does not depend on the user's syntax tree.
  • Incremental generators can also inspect syntax and semantic information through Roslyn pipelines and regenerate only when relevant inputs change.
  • Generated files usually appear under the analyzer/generated-code view rather than as ordinary hand-edited project files.

Part 4: Mini Project & Practice

Mini project: generate a static `BuildInfo` class containing a constant application name and a generated timestamp or version string supplied through build configuration.

Tip: Type the code yourself in Visual Studio 2026, run it, then deliberately change one part at a time. The goal is to understand the feature rather than simply copy the finished example.

When you are comfortable with this lesson, continue to Lesson 33.

C# in Visual Studio 2026

📘 This lesson is part of the book C# in Visual Studio 2026 by Dr. Liew Voon Kiong.

View on Amazon Kindle Edition