skip to content

A C# CLI tool built with PublishAot reports IL2026, IL2070, IL2075 and IL3050 on its reflection code; what does each mean, and how does [DynamicallyAccessedMembers] fix some?

level: seniorimportance: should knowfreq 26%

answer

  1. the trimmer follows references, not strings
  2. where did this Type come from
  3. parameter vs GetType() return value
  4. Requires* attributes bubble up
  5. annotate the flow, not the call

basics

~10 s

IL2026 and IL3050 flag calls to members marked [RequiresUnreferencedCode] or [RequiresDynamicCode]. IL2070 and IL2075 flag an unannotated Type reaching reflection; [DynamicallyAccessedMembers] on that Type keeps the named members and clears them.

solid answer

~30 s

Trimming removes members nothing references, and reflection by name hides those references. IL2026 means you called a member marked `[RequiresUnreferencedCode]`, such as `Assembly.GetTypes()`. IL3050 means you called one marked `[RequiresDynamicCode]`, such as `MakeGenericType`, whose native code AOT may not have. IL2070 and IL2075 mean a `Type` from an unannotated parameter or from `object.GetType()` reached an API like `GetProperty` that needs members kept. Annotating that parameter, generic parameter or interface with `[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicProperties)]` clears IL2070 and IL2075. The Requires* warnings need different code, such as registration instead of scanning, or the attribute bubbled up to your own API.

code

csharp · 26 lines
csharp
using System.Diagnostics.CodeAnalysis;
using System.Reflection;

var opts = new DeployOptions();
Bind(typeof(DeployOptions), opts, "Verbose", true);
BindAnnotated(typeof(DeployOptions), opts, "Region", "eu");
BindFromObject(opts, "Region", "us");
Console.WriteLine($"{opts.Verbose} {opts.Region}");

foreach (Type t in Assembly.GetExecutingAssembly().GetTypes()) { }

Type listOfOpts = typeof(List<>).MakeGenericType(opts.GetType());
Console.WriteLine(listOfOpts.Name);

static void Bind(Type type, object target, string name, object value)
    => type.GetProperty(name)!.SetValue(target, value);

static void BindAnnotated(
    [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicProperties)] Type type,
    object target, string name, object value)
    => type.GetProperty(name)!.SetValue(target, value);

static void BindFromObject(object target, string name, object value)
    => target.GetType().GetProperty(name)!.SetValue(target, value);

class DeployOptions { public bool Verbose { get; set; } public string Region { get; set; } = ""; }

go deeper

for a junior

Know that trimming removes unused code at publish and that reflection by name can make the trimmer remove members the app still needs.

for a middle

Tell the four warnings apart: two are calls to Requires-marked members, two are an unannotated Type flowing into reflection from a parameter or from GetType().

for a senior

Fix them in order of preference: annotate flows precisely, annotate an interface for GetType(), replace scanning with registration, bubble up Requires*, and suppress only with proof.

for a principal

Treat the warning count as a measure of how much behaviour is decided at run time, and set whether a library must be warning-free before it is used in trimmed or AOT apps.

## Why trimming and reflection collide **Trimming** removes code the app does not use when it is published, which shrinks the output. It is on for Native AOT (`<PublishAot>true</PublishAot>`) and can be turned on alone with `<PublishTrimmed>true</PublishTrimmed>`. The trimmer decides what is "used" by following references in the compiled code. Reflection breaks that: `type.GetProperty("Verbose")` names a member with a string, on a `Type` that may only be known at run time, so the trimmer cannot see that `Verbose` is needed. **Native AOT** adds a second limit: all native code is generated at publish, so a generic instantiation first invented at run time may have no code. The SDK reports these risks as **analysis warnings**. Roslyn analyzers show them during `dotnet build` when `PublishAot`, `PublishTrimmed`, `IsTrimmable` or `EnableTrimAnalyzer` is set (`IsAotCompatible` turns on the trim and AOT analyzers for a library), and the publish step reports them again. A file-based app run with `dotnet run app.cs` on the .NET 10 SDK has `PublishAot` on, so the snippet above printed all four warnings on an ordinary run. ## What each warning means | Id | Raised when | Example in the snippet | |---|---|---| | **IL2026** | you call a member marked `[RequiresUnreferencedCode]`, one the trimmer cannot make safe | `Assembly.GetTypes()`: "Types might be removed." | | **IL2070** | a `Type` **parameter** with no annotation reaches a reflection API that needs members kept | `Bind(Type type, ...)` calling `type.GetProperty(name)` | | **IL2075** | the **return value of a method**, here `object.GetType()`, reaches such an API | `target.GetType().GetProperty(name)` | | **IL3050** | you call a member marked `[RequiresDynamicCode]`, which may need native code AOT did not generate | `typeof(List<>).MakeGenericType(...)` | IL2070 and IL2075 are the same complaint with different sources. `Type.GetProperty(string)` declares, through an annotation on its `this` parameter, that the `Type` it runs on must have its public properties kept. The analyzer traces where your `Type` came from. If it came from an unannotated parameter (IL2070) or from `GetType()` (IL2075), nothing guarantees that. ## The fixes, from best to last resort 1. **Annotate the flow with `[DynamicallyAccessedMembers]`.** Put it on the `Type` parameter, field, return value or generic parameter that feeds reflection, naming exactly what you touch: `DynamicallyAccessedMemberTypes.PublicProperties`, `PublicParameterlessConstructor`, `PublicMethods` and so on. `BindAnnotated` in the snippet raises no warning. The requirement moves to its callers, and a caller that passes `typeof(DeployOptions)` satisfies it, because the trimmer can see that type and keep its public properties. 2. **Annotate a type to cover `GetType()`.** `[DynamicallyAccessedMembers]` is also allowed on classes, structs and interfaces. Put it on `ICommand` and `cmd.GetType().GetProperty(...)` on an `ICommand` no longer raises IL2075 (second snippet). The IL2075 docs explain the cost: an annotation on a type definition roots the named members on that type and on all its derived or implementing types, so keep it as narrow as possible. 3. **Replace discovery with registration.** `Assembly.GetTypes()` has no annotation that makes it safe. A generic `Register<[DynamicallyAccessedMembers(PublicParameterlessConstructor | PublicProperties)] T>()` lets each command be listed once, and `Activator.CreateInstance(typeof(T))` and `typeof(T).GetProperties()` inside it are warning-free. A source generator can write that list for you. 4. **Bubble the requirement up.** If a library method really cannot be made safe, mark it `[RequiresUnreferencedCode("...")]` or `[RequiresDynamicCode("...")]`. Warnings inside it are silenced, and every caller gets IL2026 or IL3050 with your message. 5. **Suppress only with proof.** `[UnconditionalSuppressMessage]` survives into the compiled assembly and is honoured by the trimmer. `#pragma warning disable` and `[SuppressMessage]` exist only in source, so they can silence the build-time analyzer but not the publish-time warning. Either way, a suppression does not keep the member; if it was wrong, the property is gone at run time. ## What goes wrong at run time if you ignore them - A trimmed app's `GetProperty("Verbose")` can return `null` because the property was removed, and the binder silently skips the option or throws `NullReferenceException`. - A discovery scan finds fewer command types than it did in a JIT build. - Under Native AOT, a `MakeGenericType` call for an instantiation with no generated code throws when it runs. The docs on AOT warnings say that, ideally, a Native AOT app has **no** AOT warnings, and that if any remain you should test the published app thoroughly for behaviour changes rather than assume it matches the JIT build. ## Reading the warnings as design feedback These warnings point at code whose behaviour depends on information only available at run time. The durable fixes make that information static: a `Type` known at the call site, a registration list, or generated code. This is why reflection-heavy libraries ship annotated APIs or source-generated alternatives. Choosing to move a whole library to generators is a decision covered with source generators.

  • Why does `#pragma warning disable IL2070` not make the trimmed app safe?
    A pragma lives only in source, so it can silence the build-time analyzer, but the trimmer works on compiled IL and reports again at publish. Even `[UnconditionalSuppressMessage]`, which the trimmer does honour, only hides the message; it does not keep the property. The fix that keeps the member is a `[DynamicallyAccessedMembers]` annotation on the `Type` that flows into `GetProperty`.
  • Which `DynamicallyAccessedMemberTypes` does a generic `Register<T>()` need when it calls `Activator.CreateInstance(typeof(T))` and `typeof(T).GetProperties()`?
    `PublicParameterlessConstructor` for the creation and `PublicProperties` for the property list, combined with `|`. Asking for `All` would also silence the warnings, but it keeps every member of the type and its nested types, which bloats the output and can pull in other members that need their own annotations. Name only what the code touches.

  • Trim warnings only matter for ASP.NET Core apps
  • #pragma warning disable makes reflection safe after trimming
  • IL2075 goes away if GetProperty is given explicit BindingFlags
  • DynamicallyAccessedMemberTypes.All is the right default annotation
  • IL3050 is fixed by adding [DynamicallyAccessedMembers]
  • If the app runs under dotnet run, the published AOT build will behave the same