Introduction

When I think about native binaries with .NET, many devs immediately picture compact executables, ultra-fast at startup, ready for serverless. Reality is more nuanced. Native AOT (Ahead-Of-Time compilation) is powerful — but it is not always the answer. You can compile C# to native code, yes. But what is the real price? How does it work internally? And in which scenarios does it really make sense to invest compile time, accept reflection limitations and ship larger binaries?

I created this article because I saw many devs trying to use Native AOT without measuring the full trade-off. In this guide, I will walk through the compilation stack from the C# code processed by Roslyn to the native code emitted by the ILC and show which constraints need to be part of the decision. Part 2 of this series complements the concepts with reproducible measurements of build, size, startup, throughput and memory.

Prerequisites

  • C# and .NET knowledge: experience with .NET 8+ and familiarity with concepts such as assemblies, IL (Intermediate Language) and garbage collection.
  • .NET SDK 9.0+: the article focuses on .NET 9 and .NET 10 (LTS).
  • Compilation basics: understanding the differences between JIT (Just-In-Time) and ahead-of-time compilation helps, but I will explain the concepts as needed.
  • Familiarity with performance: interpreting basic startup, memory footprint and throughput metrics.

What Native AOT is

Native AOT means compiling your C# code into a native binary before running it, not during execution. Contrast this with the traditional model:

JIT (Just-In-Time):

  1. You write C# and compile it to IL (Intermediate Language)
  2. When the app starts, the JIT takes the IL
  3. The JIT turns IL into machine code dynamically as the code runs
  4. The .NET runtime (including the JIT, the GC and all libraries) runs in memory

Native AOT:

  1. You write C# and compile it to IL
  2. On the build machine, the NativeAOT toolchain takes the IL, performs static analysis and removes unnecessary code (trimming)
  3. It turns everything into native machine code (x86-64, ARM, etc.) before you run it
  4. The result is a self-contained executable — no JIT and no need for a prior .NET installation, but with the required parts of the runtime

💡 Tip: Native AOT includes a reduced version of the required parts of CoreCLR and the libraries, such as the GC and the allocator. “No installed runtime” is correct; “no runtime” is not.

Compilation Variations

There is a spectrum between pure JIT and pure AOT:

  • Default JIT (Tier 0): compiles everything at startup; later optimizes with Tier 1 according to usage
  • ReadyToRun (R2R): partial ahead-of-time compilation; still needs the runtime, and the JIT is available for code that was not precompiled
  • Full Native AOT: everything precompiled; no JIT (constrained by trimming and static analysis)

Native AOT is the most aggressive in trade-offs: extreme startup gains, but strict reflection constraints.

Visual comparison of JIT, R2R and Native AOT showing how much compilation happens ahead of time and when the runtime is still needed

Compilation Stack: From Roslyn to Native Binary

This is the technical heart of the topic. I will describe exactly what happens when you run dotnet publish -c Release --self-contained -r win-x64 /p:PublishAot=true.

1. Static Analysis with Roslyn

Roslyn is Microsoft’s C# compiler. It:

  • Reads .cs files
  • Builds a syntax tree (AST)
  • Resolves types, namespaces and symbols
  • Generates IL (Intermediate Language) — platform-agnostic pseudocode

For Native AOT, Roslyn does nothing special at this stage — the IL emission is identical. The “magic” happens later.

2. IL (Intermediate Language)

IL is like the “universal bytecode” of .NET. A simple example:

1
public int Add(int a, int b) => a + b;

Becomes IL like this:

1
2
3
4
5
6
.method public int32 Add(int32 a, int32 b) cil managed {
  ldarg.0
  ldarg.1
  add
  ret
}

This is platform-agnostic. Any processor can execute these instructions (with a VM or a compiler).

3. ILCompiler & Trimming (Reachability Analysis)

ILCompiler is the core of the Native AOT magic. It:

  1. Reads the IL generated by Roslyn
  2. Analyzes reachability: it starts at the entry point (Main) and follows every call and every accessed field. “If Main calls Foo(), and Foo() calls Bar(), then Bar() is reachable.”
  3. Removes unnecessary code — tree-shaking. If MetodoX is never called, it is deleted from the final executable.
  4. Detects problematic reflection: if you write Type.GetType("MinhaClasse"), the compiler cannot know statically which type you want. That is a problem.
  5. Emits native code with the ILC using the RyuJIT backend

4. ILC and the RyuJIT backend

The ILC drives the Native AOT compilation and uses the RyuJIT backend to turn IL into native code for x86-64, ARM64 and other compatible architectures. crossgen2 belongs to the pipeline most associated with ReadyToRun and is not a step of the Native AOT publish described here.

It is not the traditional JIT (which runs at execution time). It is an offline compiler, with more time for optimization.

Output: .obj files (native objects), later linked into the final executable.

5. Linking & Final Executable

The .obj files are linked with:

  • Runtime libraries (.NET GC, allocators, etc.)
  • Linked standard library (Collections, I/O, etc.)
  • Your compiled code

Result: app.exe on Windows or an executable without an extension on Linux. The publish is self-contained: it does not require a prior .NET installation, but it includes the required parts of the runtime and may depend on native operating system libraries.

Complete Visual Flow

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
C# Code
  ↓
[Roslyn Compiler]
  ↓ (emits)
IL (Intermediate Language)
  ↓
[ILCompiler - Reachability Analysis & Trimming]
  ↓ (removes dead code)
Optimized IL
  ↓
[ILC / RyuJIT backend]
  ↓ (turns into)
Native Code (.obj files)
  ↓
[Linker]
  ↓ (linked with runtime)
Self-contained executable (app.exe / app)

📝 Example: A simple “Hello World” app with JIT takes ~100MB (runtime + libs). With AOT, the executable alone is ~5MB.

Trimming and Static Analysis: The Big Obstacle

Trimming is where Native AOT shines — and where it breaks.

The Reflection Problem

Reflection lets code discover types, fields and methods at runtime:

1
2
3
4
// Classic reflection
Type tipo = Type.GetType("MyApp.MyClass");
MethodInfo method = tipo.GetMethod("MyMethod");
object result = method.Invoke(instance, params);

Why does this break AOT? The static compiler cannot know at build time which type you will request in Type.GetType(). So, to be safe, it either:

  • Compiles all types (increasing the binary)
  • Or fails at runtime (crash)

Solution: TrimmerRootAssembly and Attributes

Microsoft provides MSBuild configuration and attributes to tell the trimmer which members must be preserved:

1
2
3
<ItemGroup>
  <TrimmerRootAssembly Include="AssemblyComReflection" />
</ItemGroup>
1
2
3
4
5
6
static void ProcessType(
    [DynamicallyAccessedMembers(
        DynamicallyAccessedMemberTypes.PublicMethods)] Type tipo)
{
    // The public methods of "tipo" will be preserved.
}

These mechanisms do not make any code automatically AOT-compatible. They make explicit the parts of the graph that static analysis could not infer, and they still require testing the published artifact.

Conservative vs Aggressive Analysis

  • Conservative: the trimmer assumes any Type.GetType() may be used and keeps everything (larger binary, but safe)
  • Aggressive: the trimmer removes everything not proven reachable (smaller binary, but it may break at runtime)

Articles about Native AOT always recommend “test a lot” — and rightly so.

Performance Trade-offs

Native AOT is not a silver bullet. These are the real trade-offs:

1. Startup: a frequent Native AOT advantage

Native AOT removes JIT compilation during execution and often reduces the time to the first response. In the Part 2 lab, the median was 63.794 ms for Native AOT and 587.644 ms for framework-dependent JIT over 30 processes. These values describe a specific workload, hardware and environment; in managed serverless, the cold start also includes provider decisions, sandbox, networking and configuration.

⚠️ Warning: AOT puts all the compilation time on the build machine, not on the client. If it takes 15 minutes to compile your app with AOT, well… there are trade-offs.

2. Memory and distribution size

A framework-dependent JIT publish can have few files because it assumes a compatible runtime installed outside the artifact. Self-contained JIT, self-contained ReadyToRun and Native AOT include the required runtime, so the comparison must use equivalent units. In the Part 2 lab, Native AOT took 28.3 MB uncompressed and a 41 MB median maximum working set; JIT FDD took 165.7 KB of artifact, not counting the installed runtime, and a 103 MB median maximum working set.

These numbers do not establish a universal ratio. Dependencies, generics, resources, symbols, code preserved for reflection and the pages actually touched change both the size and the resident memory.

3. Throughput and Optimization

AspectJITAOT
TieringYes (Tier 0 → 1 optimization)No (fixed)
ProfilingThe JIT adjusts according to usageStatic (no profiling)
Hot pathImproves over timeFixed (no warm-up)

The JIT has an adaptation advantage in long-running processes because tiered compilation and dynamic PGO can observe hot types and paths and recompile methods. That does not guarantee a win: Native AOT can tie or beat the JIT in specific, stable workloads. Throughput, tail latency, CPU and memory must be measured in the real application.

Summary: When to Use It?

  • First response and short-lived processes: compare Native AOT and ReadyToRun, also measuring publish, distribution and compatibility.
  • Warm throughput and latency: compare JIT with tiering/dynamic PGO and Native AOT under the same load.
  • Density and operations: include RSS/working set, shared runtime, observability, plugins and update frequency.

Practical Example: CLI Tool with Native AOT

I will show a real example: a String Analyzer CLI that counts character frequency in files.

The reason for choosing a CLI: minimal reflection, pure I/O, ideal for AOT.

Project Structure

1
2
3
4
5
6
7
BlogSamples/
├── NativeAot/
│   ├── CliExample/
│   │   ├── StringAnalyzer.Console.csproj
│   │   ├── Program.cs
│   │   ├── AnalyzerService.cs
│   │   ├── README.md

.csproj File with AOT Enabled

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net10.0</TargetFramework>
    <Nullable>enable</Nullable>
    <PublishAot>true</PublishAot>
    <TrimMode>link</TrimMode>
    <RuntimeIdentifiers>win-x64;linux-x64;osx-arm64</RuntimeIdentifiers>
    <SelfContained>true</SelfContained>
  </PropertyGroup>
</Project>

Highlights:

  • PublishAot=true enables the Native AOT compiler
  • TrimMode=link enables aggressive trimming
  • RuntimeIdentifiers lists the target platforms
  • The project does not add external dependencies

Example Code: Program.cs

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
string[] commandArguments = Environment.GetCommandLineArgs();
if (commandArguments.Length < 2)
{
  Console.Error.WriteLine("Uso: StringAnalyzer.Console <arquivo>");
  return 1;
}

string filePath = commandArguments[1];
if (!File.Exists(filePath))
{
  Console.Error.WriteLine($"Arquivo '{filePath}' não encontrado.");
  return 1;
}

var analyzer = new AnalyzerService();
AnalysisResult result = analyzer.Analyze(filePath);
Console.WriteLine($"Total de caracteres: {result.TotalChars:N0}");
return 0;

Why this is AOT-friendly:

  • Explicit parsing with standard library APIs
  • No dynamic assembly loading or code emission
  • Simple I/O, no advanced patterns

Build and Run

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
# Restore
dotnet restore

# Publish for AOT (windows x64)
dotnet publish -c Release -r win-x64 /p:PublishAot=true

# The executable is written to: bin/Release/net10.0/win-x64/publish/StringAnalyzer.Console.exe
# Typical size: 8–12 MB

# Test
./StringAnalyzer.Console.exe myfile.txt

📂 Source Code: The complete example is available in the blog’s samples repository: BlogSamples/NativeAot/CliExample/

Tips and Good Practices

  1. Prefer explicit parsing or a library validated for AOT The example uses only standard library APIs. When adopting a CLI library, publish and test the Native AOT artifact to detect dynamic reflection or trimming warnings.

  2. Minimize reflection; use source generators when possible If you need serialization, use System.Text.Json with source generators (JsonSourceGenerationContext). Avoid Newtonsoft.Json or pure reflection with AOT.

  3. Check AOT warnings during development Build with dotnet build and check the warnings. Do not wait to discover problems in production. Use -Werror to turn warnings into errors in CI.

  4. Measure the distribution size Compare the published directory and the compressed artifact, stating whether the runtime is included. Sometimes removing a dependency saves more than changing the compilation mode.

  5. Consider ReadyToRun as an alternative If you want fast startup but cannot give up reflection, ReadyToRun is a middle ground. Build with PublishReadyToRun=true instead of PublishAot=true.

  6. Test in production-like environments An AOT binary compiled on Windows may not run on Linux (object files link differently). Always build and test for the specific target runtime.

  7. Compare equivalent units A framework-dependent IL assembly excludes the installed runtime, while Native AOT is self-contained. For edge, IoT or frequent updates, compare the bytes actually transferred and the total storage.

  8. Document AOT compatibility of dependencies If you use third-party libraries, explicitly confirm that they are AOT-compatible. Keep that in your deployment README.

Objective Summary

  • Native AOT — ahead-of-time compilation of C# into native code for a specific RID, removing the JIT at runtime and including the required parts of the runtime without requiring a prior .NET installation.

  • Compilation stack — Roslyn generates IL; the ILC analyzes reachability and compatibility, uses the RyuJIT backend to emit native code and hands objects to the platform linker.

  • Trimming — automatic removal of unreachable code (tree-shaking); it breaks with dynamic reflection (Type.GetType()) and requires TrimmerRootAssembly and DynamicallyAccessedMembers to inform the compiler.

  • Startup time — Native AOT removes JIT work at runtime, but the gain must be measured on the real hardware and hosting environment.

  • Throughput — JIT with tiering and dynamic PGO adapts hot code at runtime; Native AOT can tie or win in specific workloads, so there is no universal result.

  • Metrics-driven decision — first response, p95/p99, throughput, CPU, resident memory, distribution size, compatibility and build time must come before labels such as CLI or server.

  • Trade-offs — startup, memory, size, throughput, compatibility and build time vary with the workload; the decision requires measuring equivalent distributions.

Read Also

References