Trimming and dynamic access
Trimming and dynamic access
Trimming removes code that the publishing tools determine is unnecessary. Reflection can make member use difficult to predict. Native AOT additionally compiles managed code ahead of time into native code and restricts runtime code generation. Ordinary execution success does not prove a trimmed or AOT build will work.
Examples target the proposed C# 14 / .NET 10 console baseline (one independent Program.cs per example, nullable enabled). Expected outputs are reasoned, not executed. Source-generation examples require the standard SDK and its built-in generators; no extra packages or external services are used.
Prefer known contracts
When the set of supported types is small, a direct factory can express all choices in ordinary code. This keeps constructors visible to static analysis and makes unexpected inputs explicit.
using System;Console.WriteLine(Create("short").Format("A1"));static IFormatter Create(string kind) => kind switch{ "short" => new ShortFormatter(), _ => throw new ArgumentException("Unknown formatter")};interface IFormatter { string Format(string code); }sealed class ShortFormatter : IFormatter{ public string Format(string code) => code;}The switch maps an approved input to a known implementation. No assembly or type is loaded by name.
Expected output (reasoned, not executed):
A1Express a reflection requirement
DynamicallyAccessedMembers communicates which members a Type value must retain. An annotation is a dataflow contract: callers must provide types satisfying it, and the trimmer can warn when it cannot establish that. It is not a runtime validation check.
using System;using System.Diagnostics.CodeAnalysis;using System.Reflection;PrintPropertyCount(typeof(StockItem));static void PrintPropertyCount( [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicProperties)] Type type){ Console.WriteLine(type.GetProperties(BindingFlags.Public | BindingFlags.Instance).Length);}sealed class StockItem{ public string Code { get; set; } = "A1"; public int Quantity { get; set; }}The annotation states the required public-property access. The count is expected in a normal build; the trimmed build and its warnings must be verified separately.
Expected output (reasoned, not executed):
2Mark incompatible dynamic behavior
RequiresUnreferencedCode marks an API whose behavior may fail after trimming; RequiresDynamicCode marks a potential runtime code generation requirement for AOT analysis. Neither attribute makes the method compatible. This fixture intentionally contains a conceptual incompatibility marker, but never calls the marked method.
using System;using System.Diagnostics.CodeAnalysis;Console.WriteLine("static path");static class OptionalIntegration{ [RequiresUnreferencedCode("External metadata cannot be predicted.")] public static void InspectExternalMetadata() => throw new NotSupportedException("Illustrative boundary only");}The marked method is a deliberately nonfunctional placeholder, not a plugin loader. Calling a marked member in trim analysis may produce IL2026; no diagnostic or publish result was measured.
Expected output (reasoned, not executed):
static pathCommon mistakes and edge cases
Do not suppress trim or AOT warnings to make a build look clean. Preserve only necessary members, prefer known contracts and source generation, and test the actual published artifact on each supported RID. AssemblyLoadContext controls loading and possible unloading of trusted plugins; it is not a security boundary, and Native AOT does not support general dynamic assembly loading. Never load unknown binaries in a learning lab.
Practice and recap
A reviewed app uses typeof(StockItem) to read public properties, and another path accepts arbitrary plugin names. Choose an approach for each if targeting Native AOT.
Hint: Separate finite known types from open-ended runtime loading.
Learning objective: Identify reflection assumptions that require testing. See accompanying manual practice and knowledge check.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Trimming and dynamic access — knowledge check
Apply the lesson concepts to the following scenarios.
What is trimming intended to remove?
What does DynamicallyAccessedMembers communicate?
What can RequiresUnreferencedCode do?
What is a Native AOT limitation?
How should compatibility be established?