Ahead Of Time (AOT) compilation to native code using C#

Munib ButtSenior .NET/Azure Developer/Analyst Consultant
CERTIFIED EXPERT
Senior technical systems architect/ analyst and developer/mentor with over 30 years’ experience (20+ years in Canada)
Published:
Microsoft has just released .NET 7 on 14th November 2022. One of the cool feature introduced with .NET 7/C# 11  is the Ahead of Time (AOT) compilation to native code feature. It allows us to directly compile and publish our code in the native version. Hence, no Just in Time (JIT) compilation.
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.
 
 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!");

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:



Remember to add the "Desktop Development for C++" workload.

Now, publish the application using Terminal in Visual Studio as below:


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.
0
514 Views
Munib ButtSenior .NET/Azure Developer/Analyst Consultant
CERTIFIED EXPERT
Senior technical systems architect/ analyst and developer/mentor with over 30 years’ experience (20+ years in Canada)

Comments (0)

Have a question about something in this article? You can receive help directly from the article author. Sign up for a free trial to get started.