Ahead Of Time (AOT) Compilation To Native Code In .NET 7

Introduction

Microsoft has just released .NET 7 on 14th November 2022. In the previous articles, we looked at some of the new features.

Today, we will look at another feature introduced with .NET 7 and that is the Ahead of Time (AOT) compilation to native code.

AOT compilation to native code

In standard .NET development, we compile and build our code to Intermediate Language (IL). Then, when we run the application, the JIT (Just-In-Time) compiler, compiles it to native code and runs it. This is the reason for the slight delay we see when we first run an application. With the new feature in .NET 7, we can compile our code directly to the native version and hence the first run is also very fast. The process to do this is quite simple and we will look at it below. Let us create a console application using Visual Studio 2022 Community edition.

Ahead Of Time (AOT) compilation to native code in .NET 7

Ahead Of Time (AOT) compilation to native code in .NET 7

Ahead Of Time (AOT) compilation to native code in .NET 7

Now, add the below code to the “Program.cs” file.

List<string> names = new List<string> { "John Smith", "Jane Smith" };
foreach(var name in names){
    Console.WriteLine(name);
}
Console.WriteLine("Process Complete!");

If we run the application, we get the below,

Ahead Of Time (AOT) compilation to native code in .NET 7

We can run the compiled application as below,

Ahead Of Time (AOT) compilation to native code in .NET 7

These take a few seconds to run the first time.

Next, open the project file and update as below:

Ahead Of Time (AOT) compilation to native code in .NET 7

After this change, I try to publish the application for Windows as below,

Ahead Of Time (AOT) compilation to native code in .NET 7

However, we get the error message that the workload “Desktop Development for C++” is required. Let us add this workload.

Ahead Of Time (AOT) compilation to native code in .NET 7

After this, I publish again, this time using the terminal in Visual Studio.

Ahead Of Time (AOT) compilation to native code in .NET 7

All works fine and the output file is generated. When I run this file, it runs very quickly, even the first time, as it has been compiled to native code.

Ahead Of Time (AOT) compilation to native code in .NET 7

Summary

In this article, we looked at a new feature that has been introduced with .NET 7. Using AOT can make our applications much faster to run from the first time. However, there are still some major limitations on creating AOT compiled native applications. For one, only console applications can be done at this time. ASP.NET applications are not supported. In addition to these, there are some other limitations as well. I would recommend reading the Microsoft article on this subject before creating your application to ensure all its features are compatible with AOT.


Recommended Free Ebook
Similar Articles