AddSource
Learn to add generated code to the compilation with AddSource.
AddSource
The AddSource(hintName, source) method adds generated C# code to the compilation. hintName is a unique file name (usually with a .g.cs extension); source is the generated code text.
This is the final step where the generator hands its output to the compiler. Each call is treated like a separate source file and becomes part of the compilation.
Keeping a source list
In this lesson we define a static class called SourceEmitter. Its AddSource method appends the generated code to a List<(string, string)>; this list simulates the additional source files in a real compilation.
This approach lets us see which files the generator produced through console output. The list preserves insertion order.
Exercise Add sources with SourceEmitter
Define a static class SourceEmitter. Give it a public static List<(string Hint, string Source)> Sources { get; } = new(); property and a public static void AddSource(string hintName, string source) method (with Sources.Add((hintName, source));). In Main, add two items: SourceEmitter.AddSource("UserDto.g.cs", "public class UserDto { }") and SourceEmitter.AddSource("OrderDto.g.cs", "public class OrderDto { }"). Then print each entry.Hint with foreach.
Show example solution
static class SourceEmitter { public static List<(string Hint, string Source)> Sources { get; } = new(); public static void AddSource(string hintName, string source) { Sources.Add((hintName, source)); } }. In Main: two AddSource calls, foreach (var entry in SourceEmitter.Sources) Console.WriteLine(entry.Hint);
Example solution:
using System;
using System.Collections.Generic;
static class SourceEmitter
{
public static List<(string Hint, string Source)> Sources { get; } = new();
public static void AddSource(string hintName, string source)
{
Sources.Add((hintName, source));
}
}
class Program
{
static void Main()
{
SourceEmitter.AddSource("UserDto.g.cs", "public class UserDto { }");
SourceEmitter.AddSource("OrderDto.g.cs", "public class OrderDto { }");
foreach (var entry in SourceEmitter.Sources)
{
Console.WriteLine(entry.Hint);
}
}
}
Test yourself
-
What does the first parameter of AddSource specify?
- The generated code content
- The hint name
- The class name
- The namespace
Show answer
The hint name — Correct. The first parameter is the hint name (file name).
-
Match each AddSource parameter
- hintName
- Unique file name
- source
- Generated code text
- .g.cs
- Generated file extension
-
Complete the AddSource call
SourceEmitter.AddSource("UserDto____", "public class UserDto { }");Show answer
SourceEmitter.AddSource("UserDto.g.cs", "public class UserDto { }");