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.
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,
We can run the compiled application as below,
These take a few seconds to run the first time.
Next, open the project file and update as below:
After this change, I try to publish the application for Windows as below,
However, we get the error message that the workload “Desktop Development for C++” is required. Let us add this workload.
After this, I publish again, this time using the terminal in Visual Studio.
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.
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.