Trimming & Native AOT Warnings (`[RequiresUnreferencedCode]`)
1Concept
Modern .NET trimmers strip unused metadata to produce small Native AOT binaries. Reflection patterns that inspect unreferenced types require `[RequiresUnreferencedCode]` and `[DynamicallyAccessedMembers]` annotations to prevent trimmer stripping.
2Architecture Diagram
Native AOT Compiler
│
Scans Code Graph ──> Unreferenced Type stripped to save binary size!
│
Caller attempts Reflection ──> Crashes at runtime if not annotated!3Code Example
C# 13 & .NET 9
using System;
using System.Diagnostics.CodeAnalysis;
public class AotTrimmingDemo
{
[RequiresUnreferencedCode("Uses reflection to serialize types dynamically.")]
public static void SerializeDynamic(object data)
{
Console.WriteLine($"Serializing: {data.GetType().Name}");
}
public static void Main()
{
SerializeDynamic("SampleString");
}
}4Expected Output
Serializing: String
5Key Takeaways
- ✓Annotate dynamic reflection methods with `[RequiresUnreferencedCode]`.
- ✓Use `[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicProperties)]` on Type parameters.
- ✓Prefer Roslyn Source Generators to achieve 100% Native AOT compatibility.