C# Reference ยท Reflection, Attributes and Metadata
Native AOT and trimming
Reference for Native AOT and IL trimming in .NET: what they remove, why reflection breaks, and the annotations that keep code safe: DynamicallyAccessedMembers and more.
Normally a .NET program ships as IL and the just-in-time (JIT) compiler turns it into machine code while it runs. Two publishing options change that. Trimming removes code that the build can prove is never used, so the deployed app is smaller. Native AOT (ahead-of-time) goes further: it compiles everything to a self-contained native executable, with no IL and no JIT at runtime. Start-up is faster and memory use is lower, but the compiler must know the whole program in advance.
Both options work by static analysis, and that is why they clash with reflection. If code asks for a type or member by a string or a runtime value, the analyzer cannot see what will be needed and may remove it. The rules below are about helping the tools: annotate the places where code reflects, avoid runtime code generation, and prefer compile-time techniques such as source generators.
Publishing with trimming or Native AOT needs the .NET SDK, MSBuild and a native toolchain. The code runner on this site only compiles and runs on the JIT, so the project settings below are shown read-only, and the examples demonstrate the annotations and the checks you can run in normal code.
<!-- .csproj --> <PropertyGroup> <PublishTrimmed>true</PublishTrimmed> <!-- trim unused IL --> <PublishAot>true</PublishAot> <!-- Native AOT; also turns on the analyzers --> <IsTrimmable>true</IsTrimmable> <!-- mark a library as safe to trim --> </PropertyGroup>
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.
What changes
Trimming
The trimmer starts at your entry point, follows every call it can prove, and drops the rest of every assembly, including the framework. Reflection that uses constants is understood: typeof(Customer).GetProperties() keeps the public properties of Customer. Reflection over values it cannot see through is not: Type.GetType(name) with a name read from a file, Assembly.GetTypes() or MakeGenericType on unknown types may find that the member was removed.
The SDK reports these cases as warnings with IL codes (for example IL2026 for a call to a method marked RequiresUnreferencedCode, and IL2070 to IL2111 for type values that reach reflection without a promise). Treat trim warnings as bugs: the app can run in testing and fail in production.
Native AOT
Native AOT keeps all the trimming rules and adds more:
- No runtime code generation.
System.Reflection.Emitfor new types,Expression.Compile()(the interpreter is used instead, which is slower),DynamicMethodandMakeGenericTypeover value types that were not seen at compile time are unsupported or limited. Look forRequiresDynamicCodewarnings (IL3050). - No assembly loading from disk at runtime and no
Assembly.LoadFrom; all code must be known at publish time. - No C++/CLI, no built-in COM, no
AppDomainunloading. - Platform specific. The output is a native binary for one runtime identifier such as
linux-x64orwin-x64.
What keeps working
Plain C#, generics, LINQ, async, collections, System.Text.Json with a source-generated context, and LibraryImport P/Invokes work as usual. Libraries opt in with IsTrimmable and IsAotCompatible, which enable the analyzers on build.
Syntax
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes types)] [RequiresUnreferencedCode(string message)] [RequiresDynamicCode(string message)] [RequiresAssemblyFiles(string message)] [UnconditionalSuppressMessage(string category, string checkId)] [DynamicDependency(string memberSignature, Type type)]
| Attribute | Meaning |
|---|---|
DynamicallyAccessedMembers |
On a Type, string (a type name) or generic parameter: the value will be used with reflection to reach the listed kinds of members, so keep them. Callers must pass a type that the trimmer can analyze. |
RequiresUnreferencedCode |
The method is not safe to trim. Calling it produces IL2026 until the caller is annotated or suppresses the warning. |
RequiresDynamicCode |
The method generates code at runtime and does not work in Native AOT (IL3050). |
RequiresAssemblyFiles |
The method needs assembly files on disk, which single-file apps do not have (IL3002). |
UnconditionalSuppressMessage |
Silences a warning in a place where you have verified safety. Use sparingly, with a justification. |
DynamicDependency |
Tells the trimmer to keep a named member when this member is kept. |
Usage notes
- Prefer
typeofand generics over names in strings.typeof(T)flows through the analyzer;Type.GetType("My.Type")does not. - Annotate instead of suppress. Put
DynamicallyAccessedMemberson the parameter or type parameter that reaches reflection, then every caller is checked. Suppression only hides the problem. - Source generators are the AOT-friendly replacement for reflection. Serializers, dependency-injection registrations, logging and regex (
[GeneratedRegex],[JsonSerializable],[LoggerMessage]) move the work to build time. They do not run on this site's runner; see Source generators. - Reflection-based serialization in
System.Text.Jsonis disabled in trimmed apps by default (JsonSerializerIsReflectionEnabledByDefaultis false whenPublishAotis set). Pass a generatedJsonSerializerContextinstead. - Test the published app. A passing
dotnet runsays nothing about the trimmed or AOT build. Run your tests, or at least a smoke test, against the published output. - Size and speed. Typical gains are a much faster start (no JIT warm-up) and a smaller memory footprint. Peak throughput can be lower than a JIT with dynamic profile-guided optimization, so measure.
- ASP.NET Core: minimal APIs and gRPC can be published with AOT; MVC controllers with runtime discovery and Razor view compilation cannot.