0Pricing
C# Academy · Lesson

Native AOT Compilation

Enable Native AOT in a .NET project, understand trim analysis, and publish a self-contained native binary.

Native AOT Compilation is a free C# Academy lesson on CoddyKit — lesson 1 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the C# Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

What Is Native AOT?

Native Ahead-of-Time (AOT) compilation compiles your .NET app into a self-contained native binary at publish time. There is no JIT compiler, no .NET runtime needed on the target — just a single executable.

When to Use Native AOT

Native AOT shines for microservices, CLI tools, and serverless functions where startup time and memory footprint matter. It is not ideal for apps that rely heavily on runtime reflection.

// Ideal use cases:
// - Serverless functions (AWS Lambda, Azure Functions)
// - High-throughput microservices (fast cold start)
// - CLI tools shipped as single-file executables
// - IoT / embedded scenarios

// Poor fit:
// - Apps using extensive reflection (e.g., dynamic proxies)
// - Apps loading plugins at runtime
// - Apps depending on libraries that don't support trimming

// Key benefits:
// - Sub-10ms startup time (vs 200-500ms for JIT)
// - Lower memory at startup (no JIT overhead)
// - Smaller attack surface (no JIT engine)

Publishing with Native AOT

Enable AOT in the project file and publish with dotnet publish. The output is a single native executable with no runtime dependency.

// .csproj:
<PropertyGroup>
  <PublishAot>true</PublishAot>
  <!-- Optional: disable invariant globalization for smaller binary -->
  <InvariantGlobalization>true</InvariantGlobalization>
</PropertyGroup>

// Publish for Linux x64:
dotnet publish -r linux-x64 -c Release

// Publish for Windows x64:
dotnet publish -r win-x64 -c Release

// Output: bin/Release/net9.0/linux-x64/publish/MyApp
// Single executable, no dotnet runtime required

Minimal API with Native AOT

ASP.NET Core Minimal APIs fully support Native AOT from .NET 8+. Use the dotnet new webapiaot template for a pre-configured starting point.

// dotnet new webapiaot -n FastApi

// Program.cs generated template:
var builder = WebApplication.CreateSlimBuilder(args); // AOT-optimized

// Must register serialization context for AOT:
builder.Services.ConfigureHttpJsonOptions(opts =>
    opts.SerializerOptions.TypeInfoResolverChain.Insert(0,
        AppJsonSerializerContext.Default));

var app = builder.Build();
app.MapGet("/hello", () => new Message("Hello, Native AOT!"));
app.Run();

record Message(string Text);

[JsonSerializable(typeof(Message))]
internal partial class AppJsonSerializerContext : JsonSerializerContext { }

Source-Generated JSON Serialization

Native AOT cannot use reflection-based JSON serialization. You must use System.Text.Json source generation to produce serialization code at compile time.

// Define types to serialize:
public record Product(int Id, string Name, decimal Price);
public record OrderDto(int OrderId, List<Product> Items);

// Create a JsonSerializerContext for AOT:
[JsonSerializable(typeof(Product))]
[JsonSerializable(typeof(OrderDto))]
[JsonSerializable(typeof(List<Product>))]
internal partial class MyJsonContext : JsonSerializerContext { }

// Serialize / deserialize without reflection:
var json = JsonSerializer.Serialize(product, MyJsonContext.Default.Product);
var product = JsonSerializer.Deserialize(json, MyJsonContext.Default.Product);

Trimming Warnings

Publishing with Native AOT enables trimming by default. The compiler warns when it detects code that may fail after unused code is removed. Treat trimming warnings as errors during CI.

// .csproj: treat warnings as errors in CI
<PropertyGroup>
  <PublishAot>true</PublishAot>
  <TreatWarningsAsErrors>true</TreatWarningsAsErrors>
  <TrimmerRootDescriptor>TrimmerRoots.xml</TrimmerRootDescriptor>
</PropertyGroup>

// Suppressing a specific warning when you know it is safe:
[DynamicDependency(DynamicallyAccessedMemberTypes.All, typeof(MyClass))]
public static void EnsureMyClassSurvivesTrimming() { }

// Or annotate parameters:
public static void Register(
    [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)]
    Type serviceType) { }

AOT Compatibility Analyzer

Run the AOT compatibility analyzer during development to catch incompatible code paths before they become publish-time failures.

// Enable analysis without actually publishing AOT:
<PropertyGroup>
  <EnableAotAnalyzer>true</EnableAotAnalyzer>
  <EnableTrimAnalyzer>true</EnableTrimAnalyzer>
  <EnableSingleFileAnalyzer>true</EnableSingleFileAnalyzer>
</PropertyGroup>

// Run:
// dotnet build
// => analyzer reports issues in build output

// Common warnings:
// IL2026: member uses RequiresUnreferencedCode
// IL2046: member annotated with RequiresUnreferencedCode derives from unannotated
// IL3050: member uses RequiresDynamicCode

Startup Performance Comparison

Native AOT dramatically reduces startup time and memory usage compared to JIT-compiled apps. The trade-off is longer publish time and larger executable size for some workloads.

// Typical Minimal API measurements:
// JIT (.NET 9, linux-x64):
//   Startup time:  ~180ms
//   Memory (RSS):  ~60 MB
//   Publish time:  ~5s
//   Executable:    self-contained ~80 MB

// Native AOT (.NET 9, linux-x64):
//   Startup time:  ~5ms   (36x faster)
//   Memory (RSS):  ~20 MB (3x less)
//   Publish time:  ~30s   (6x slower to build)
//   Executable:    ~10 MB (8x smaller)

// For AWS Lambda / Azure Container Apps:
// AOT cold start: <10ms vs JIT: 300-500ms = significant billing savings

Real-World: Lambda Function with AOT

A Native AOT Lambda function using the official Amazon.Lambda.RuntimeSupport package for maximum cold-start performance.

// dotnet new lambda.NativeAOT

// .csproj:
// <PublishAot>true</PublishAot>
// <StripSymbols>true</StripSymbols>

public class Function
{
    [JsonSerializable(typeof(APIGatewayProxyRequest))]
    [JsonSerializable(typeof(APIGatewayProxyResponse))]
    internal partial class LambdaContext : JsonSerializerContext { }

    static async Task Main()
    {
        Func<APIGatewayProxyRequest, ILambdaContext, APIGatewayProxyResponse>
            handler = FunctionHandler;

        await LambdaBootstrapBuilder
            .Create(handler, LambdaContext.Default.APIGatewayProxyRequest)
            .Build()
            .RunAsync();
    }

    static APIGatewayProxyResponse FunctionHandler(
        APIGatewayProxyRequest req, ILambdaContext ctx)
        => new() { StatusCode = 200, Body = "{\"status\":\"ok\"}" };
}

Quick Check

Why must you use System.Text.Json source generation instead of reflection-based serialization with Native AOT?

Recap: Native AOT Compilation

Key takeaways:

  • Native AOT compiles to a self-contained native binary — no runtime needed
  • Ideal for serverless, microservices, and CLI tools (fast startup, low memory)
  • Enable with <PublishAot>true</PublishAot> and publish with -r <rid>
  • Must use System.Text.Json source generation — reflection serialization won't work
  • Use EnableAotAnalyzer to catch compatibility issues during development
  • Trade-off: longer publish time, reflection limitations, but 5-35x faster cold start

Frequently asked questions

Is the “Native AOT Compilation” lesson free?

Yes — the full text of “Native AOT Compilation” is free to read here on the web, and the C# Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the C# Academy course, upgrade to CoddyKit PRO.

What will I learn in “Native AOT Compilation”?

Enable Native AOT in a .NET project, understand trim analysis, and publish a self-contained native binary. You practise C# Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start C# Academy?

No prior experience is required. C# Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 1 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Native AOT Compilation” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this C# Academy lesson?

Yes. Every C# Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Native AOT Compilation
  2. Trimming & Reflection Limitations
  3. ReadyToRun & Tiered Compilation
  4. Benchmarking with BenchmarkDotNet
← Back to C# Academy