skip to content

As lead of a .NET library that maps types with runtime reflection at startup, would you replace that reflection with a C# source generator, and what would it cost?

level: principalimportance: should knowfreq 32%

answer

  1. who pays, and when
  2. trim and AOT warnings
  3. only the compilation in hand
  4. Roslyn version floor
  5. keep a fallback path?

basics

~20 s

Replace it when users need trimming, Native AOT or fast start-up and their types are known at compile time. The price: a Roslyn component to maintain, a partial-type contract, build and editor cost, and no run-time-only types.

solid answer

~40 s

A generator moves type discovery from every process start into the build, emits code the trimmer and Native AOT can analyse (the reflective `GetType().GetProperties()` raises IL2075 under `PublishAot`), and surfaces many mapping mistakes at build time. In exchange the library takes on a `netstandard2.0` Roslyn component with a compiler-version floor (older SDKs report CS9057 and skip it), an incremental pipeline that must cache or it slows every user's editor, generator-driver tests, and a contract that users mark types and usually make them `partial`. It cannot see types that exist only at run time, so a reflection fallback with trimming annotations often stays. I would switch when AOT or start-up evidence justifies it, ship both paths, and retire reflection deliberately.

code

csharp · 9 lines
csharp
using System.Globalization;
CultureInfo.CurrentCulture = CultureInfo.InvariantCulture;
object p = new Price("EUR", 12.5m);
Console.WriteLine(Describe(p));

static string Describe(object o) =>
    $"{o.GetType().Name} ({string.Join(", ", o.GetType().GetProperties().Select(pi => $"{pi.Name} = {pi.GetValue(o)}"))})";

public readonly record struct Price(string Currency, decimal Amount);

go deeper

for a junior

Recall that reflection finds members while the program runs, whereas a generator writes the same code during the build.

for a middle

Explain why generated code avoids trimming warnings and start-up metadata work, and what a user must add to their types to opt in.

for a senior

Show the operational costs: Roslyn version floor and CS9057, incremental caching, generator-driver tests, and the reflective fallback with its annotations.

for a principal

Decide on evidence, start-up profiles and AOT demand, stage the migration with both paths, and own the support policy for compiler versions and emitted code.

## The decision A library that maps or describes types by **runtime reflection** (walking `Type.GetProperties()`, reading values through `PropertyInfo.GetValue`, creating objects with `Activator`) does its discovery every time a process starts. A **source generator** does the same discovery once, inside the compiler, and emits plain code. Whether to switch is a lead's call because the gains land on the library's users while most of the costs land on the library's maintainers, and because it changes the contract users write against. ## What generation buys - **Start-up work moves into the build.** The reflective path reads metadata, allocates arrays of `PropertyInfo` and reads values through them before the first mapping completes; the generated path is compiled member access. Measure it in your own start-up path rather than assuming a number, since the gain depends on how many types the library touches. - **Trimming and Native AOT become clean.** Reflection over a type the trimmer cannot see statically raises analysis warnings. Built with `PublishAot` on, `o.GetType().GetProperties()` drew **IL2075** ("'this' argument does not satisfy 'DynamicallyAccessedMemberTypes.PublicProperties' in call to 'System.Type.GetProperties()'"); the generated `Describe()` drew none, because every member it touches is named in code. - **Mistakes surface while building.** A type the generator cannot handle is reported by the generator or a companion analyzer, or fails to compile, instead of failing when the app first maps it. - **The code is readable.** Users can step into generated files, and `EmitCompilerGeneratedFiles` writes them out for review. ## What it costs | Area | Runtime reflection | Source generator | |---|---|---| | Who pays | Every process start | Every build and every editor session | | User contract | Any type works | Marked type, usually `partial`; enums and other assemblies' types need separate emitted types | | Types known only at run time | Supported | Invisible to the generator | | Trimming and AOT | Annotations and warnings | Statically analysable | | Build requirements | None | `netstandard2.0` generator, Roslyn version floor (CS9057 on older SDKs) | | Testing | Ordinary unit tests | Generator-driver tests and snapshot checks of emitted text | | Maintainer skills | Reflection API | Roslyn symbols, incremental pipelines, equatable models | Some of these deserve emphasis: 1. **Reach.** A generator sees only the compilation being built. Plugins loaded at run time, types created dynamically, or a user who cannot mark their type `partial` all need another route. 2. **Editor cost.** A careless pipeline, one that keeps symbols in its models or scans every type for a base class, slows every keystroke of every user. Incremental discipline is part of the product. 3. **Compatibility surface.** The generated code is now public behaviour: a change in what you emit is a breaking change for users who relied on it, and the generator itself must load in the oldest compiler you support. 4. **Two code paths.** A common design keeps a reflection fallback for types the generator cannot reach and mark it with the trimming annotations, which doubles what must be tested. ## What changes for users - They add the marker attribute and, for most targets, the `partial` modifier, to every type the library handles. - Their builds and editors run the generator; a slow pipeline is now a complaint about the library. - Their minimum SDK may rise, since the generator compiles against a particular Roslyn version and older compilers skip it with CS9057. - In return, AOT and trimmed publishes stop warning about the library's generated paths, and many mapping mistakes appear while building their own code. ## How to decide Lean towards generation when: - users publish with trimming or Native AOT, or you intend to support them; - start-up time matters (command-line tools, short-lived workers, scale-to-zero services) and profiling shows reflection in the start-up path; - the set of types is known at compile time and users already accept a marker attribute. Stay with reflection, or keep it as the fallback, when: - types arrive at run time or come from assemblies you do not compile; - the reflective cost is a one-off that profiling cannot find; - the team cannot yet own a Roslyn component with its own tests and version policy. ## Rolling it out - Ship the generator beside the reflective path, behind the same public API, and let users opt in with the attribute. - Add tests that run the generator through `CSharpGeneratorDriver`, compare emitted text and assert that unrelated edits leave steps `Cached`. - Publish a sample with `PublishAot` and treat any new IL warning as a regression. - Decide and document the minimum SDK, because it follows from the Roslyn version the generator compiles against. - Retire the reflective path only when telemetry or issue reports show users have moved, and say so in release notes.

  • How would you keep users who cannot mark their types partial?
    Keep the reflective path as a fallback behind the same API and annotate it for the trimmer, so AOT users get a warning rather than a silent failure. The generator can also emit a separate mapper type for a type it cannot extend, as it would for an enum, reading the type's public members through symbols instead of adding members to it.
  • What evidence would make you say no?
    A profile showing reflection is a negligible share of start-up, no users publishing with trimming or Native AOT, and types that mostly arrive from plugins at run time. In that case a generator adds build cost, a Roslyn version policy and a second code path for little measurable gain.

  • Source generators make every reflection use unnecessary, including plugins loaded at run time.
  • A generator has no cost because it runs only on the build server.
  • Switching is invisible to users, since the public API does not change.
  • Reflection works unchanged under Native AOT, so trimming is not a factor.
  • Generated code needs no tests because the compiler checks it.