What’s New in .NET 9?

Thursday, January 09, 2025

Microsoft launched .NET 9 on November 12, 2024. As the latest version in the series of .NET frameworks, it has been updated and improved compared to its successor. Microsoft and its engineering team have put in significant effort to create a framework that opens the door to a new era for software development. 

Leveraging the latest version release, a top .NET development company can easily deliver robust and versatile cross-platform applications. So, what’s new in .NET 9 that makes it a game-changer in the software development landscape? This article provides an overview of .NET 9 and a detailed discussion of its new features and major improvements. 

1. .NET 9 Overview

.NET 9 is a successor of .NET 8 and the latest version of Microsoft’s popular .NET framework. It enables developers to build robust and faster applications for various environments, such as cloud, web, desktop, and mobile. Hence, it supports cross-platform development and, is open-source.

This version of .NET enhances the speed and efficiency of the development process by promoting improved coding practices. .NET 9 comes with some major updates in performance optimizations, AI integrations, and cloud-native apps. After all, Microsoft designed new features in this version to provide better security, improved performance, and efficiency.  

2. Top .NET 9 Features and Updates

Microsoft aims to make the latest version of the .NET framework more accessible for developers. They have introduced several new features and key improvements to help developers deliver secure, high-performing applications. So, let’s take a look at what’s new in .Net 9. 

2.1 Cloud-Native Development and AI Integration

.NET takes the benefit of the rise of cloud computing and AI technologies by focusing on building intelligent applications and cloud-native apps in .NET 9. Using this new version provides access to cloud-based caching solutions, managed databases, and enhanced support for Kubernetes. These features simplify the deployment, management, and scaling of cloud-native applications. 

2.2 Enhanced Performance

A framework is not useful if it can’t provide proper performance. The development team for .NET has ensured reduced memory usage and faster execution times by optimizing the framework’s runtime. With these improvements, .NET developers can easily deploy high-performing apps where every millisecond counts. 

Here’s a tabular comparison of performance aspects between .NET versions.

Performance Aspect.NET 6.Net 7.Net 9
Startup timeFaster startup time, especially in microservices and cloud apps, thanks to its R2R.Its crossgen provides better startup time, especially in cloud apps and containers.Very less cold startup time in cloud-native and microservices applications.
Memory usage and Garbage collectionEnhanced Garbage Collection for high throughput and low latency scenarios. Also, provides heap optimization and Memory pool management.Reduces pauses with GC optimization. Also offers reduced memory fragmentation and improved memory pooling.Optimized for low latency scenarios, improved GC pause times, and heap management. Utilizes stack-based memory.
Just-in-time CompilationProvides Profile Guided Optimization and improved JIT performanceEnhanced Ahead of time compilation and JIT compilation with faster runtime performance.Reduced warm-up times and JIT compilation overhead. Also optimized for hardware accelerators.
Cross-platform performanceOffers significant cross-platform updates and improved container performance.Improved support for Linux and ARM64 and enhanced performance for microservices and cloud-native applications. Optimized for containerized workloads and offers improved cross-platform performance.
App sizeInitial code trimming and single file deploymentProvides WebSockets, optimized HTTP/2 support, and enhanced performance for ASP.NET Core applications.Dynamic linking, improved code trimming, and reduced app size for microservices and cloud-native applications.
Networking and HTTP performanceSupports HTTP/2 and HTTP/3. Provides enhanced Kestrel web server to improve HTTP performance.Continuously optimizes HTTP/3. To handle high concurrency workloads, it offers Kestrel enhancements.HTTP/3 optimization and enhanced Kestrel for high concurrency and scalable networking apps.
ASP.NET Core and web appsProvides WebSockets, optimized HTTP/2 support and enhanced performance for ASP.NET Core applications.Handles higher throughput with optimized Kestrel and provides enhanced support for cloud-native web applications.Enhanced gRPC performance, WebSocket, and other ASP.NET Core optimizations for serverless environments and web APIs.
Native interoperabilityImproved interoperability for native libraries and better P/Invoke support.Native interop optimization and enhanced P/Invoke performance for cross-platform native calls.For high-performance scenarios, offer optimized native interop. Can manage native libraries for different platforms.
Parallelism and ConcurrencyOptimized for multi-core processors and offers Improved async/await performance.Optimized concurrency and multi-threading as well as enhanced Task Parallel Library performance.Improved parallelism for high throughput apps especially Task Parallelism is optimized for large scale apps.

2.3 Improved Security Measures

Although developers implement appropriate security measures while creating applications, cyberattacks have become increasingly sophisticated. To ensure the safety of your application, .NET 9 includes essential security upgrades. It features more secure coding practices, enhanced authentication methods, and better encryption protocols. 

2.4 Elevated Developer Experience

Microsoft has excelled in creating .NET 9 to improve the overall developer experience. They knew making things easy for developers would make them more productive. So, to streamline the development workflow, Microsoft added a range of advanced features and improvements in both Visual Studio and Visual Studio Code.  These code editors provide seamless integration with .NET Aspire. 

2.5 SDK Updates

Microsoft has updated the .NET SDK in the new release to enhance build integrity, improve security, and provide better dependency management. 

  • NuGetAudit: It helps keep your projects safe by warning developers about vulnerabilities in transitive dependencies. 
  • dotnet NuGet why: This new command tells you why your project needs to use a transitive package. 
  • MSBuild BuildChecks: Enforces rules and invariants during builds. It is similar to Roslyn Analyzers but with new rules for Double Write Detection and Shared Output Path. 

2.6 Improved Cross-Platform Development

.NET 9 comes with an improved multi-platform app UI, allowing you to easily design an app with a single codebase that runs on multiple platforms such as Windows, macOS, iOS, and Android. Its Hot Reload feature allows you to make quick changes in your application to ensure a smooth experience in cross-platform app development. 

2.7 Improved Tooling for Productivity

When it comes to the .NET framework, Microsoft emphasizes user experience. Therefore, they offer better tools and updates that can enhance workflow efficiency and improve developer productivity. 

For example, before its release, .NET 9 was made available in the latest versions of Microsoft VS IDEs to ensure users receive the best coding experience. Another improvement in .NET 9 was updating its SDK to make the terminal logger the default for all terminal “interactive” sessions. 

So, the build’s console output will be formatted separately in the console logger. This not only improves the usability but also tells you the total number of failures at the end of every build. 

2.8 .NET Runtime

Feature switches that support trimming have received a new attribute model in the .NET 9 runtime. With these new characteristics, it becomes possible to create feature switches that enable libraries to toggle different areas of functionality. 

Initially, the garbage collection was implemented by Server GC to dynamically adapt to app size. But in .NET 9 this feature is enabled by default. 

Many improvements have been implemented in .NET 9, including Arm64 vectorization and code generation, inlining, and loop optimizations to enhance the performance. The UnsafeAccessorAttribute was also added to this latest version of .NET to support generic parameters.

2.9 Serialization Enhancements

.NET 9 introduces significant updates in serialization, especially in the system.Text.Json. It now offers new options such as customizable indentation characters and sizes for JSON serialization to give more readable and flexible outputs. 

On top of that, .NET 9’s JsonSerializerOptions.Web offers a singleton that allows for serialization using web defaults. This helps streamline the serialization process for web applications.  

//**Indentation Options**//
var serializeOptions = new JsonSerializerOptions
{
WriteIndented = true, //Gets or sets a value that indicates whether JSON should use pretty printing. By default, it is serialized without any extra white space.
IndentCharacter = '\t', //Defines the indentation character being used when WriteIndented is enabled. Defaults to the space character.
IndentSize = 3, //Defines the indentation size being used when WriteIndented is enabled. Defaults to two
};
string json = JsonSerializer.Serialize
(
new { OrgName = "Tatvasoft"},
serializeOptions
);
Console.WriteLine(json);

//Output:
//{
//	"OrgName":"Tatvasoft"
//}

//**Default Web Options**//
string webJson = JsonSerializer.Serialize
(
new { OrgName = "Tatvasoft"},
JsonSerializerOptions.Web // Defaults to camelCase naming policy.
);
Console.WriteLine(webJson);
//Output:
// {"orgName":"Tatvasoft"}

The above code portrays the use of .NET 9’s specific indentation setting to customize JSON serialization. It also shows how you can ensure consistent naming conventions by predefining the options for web apps. 

2.10 Cryptography

To improve cryptography, .NET 9 introduced a new one-shot hash method within the CryptographicOperations type. All the hash functions and related methods in .NET now have static one-shot implementation through APIs. It helps eliminate or reduce the allocations and optimize performance.

When .NET developers build APIs for hashing with a caller that defines the hash algorithm, it requires accepting a HashAlgorithmName argument. But implementing this pattern with one-shot APIs means trying out all the potential HashAlgorithmName until a suitable method is found. 

The .NET framework introduces the CryptographicOperations.HashData API to resolve this issue. This API creates a hash or HMAC for each input as a one-shot operation using the algorithm specified by a HashAlgorithmName. 

static void HashAndProcessData(HashAlgorithmName hashAlgorithmName, byte[] data) {
	byte[] hash = CryptographicOperations.HashData(hashAlgorithmName, data);
	ProcessHash(hash);
}

We have a specified algorithm in this method which helps simplify hashing for any given data and then processes the resulting hash. Here, we utilized a one-shot hashing capability which was introduced in .NET 9 to reduce memory allocations and improve performance. 

2.11 Libraries Updates

Numerous changes were made in the .NET libraries to improve their performance and functionalities. Here we list a few:

1. [GeneratedRegex] on Properties

With C# 13 now supporting partial properties, you can easily use the [GeneratedRegex] on properties.

[GeneratedRegex] on Properties 
[GeneratedRegex(@"^(ht|f)tp(s?)\:\/\/[0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*(:(0-9)*)*(\/?)([a-zA-Z0-9\-\.\?\,\'\/\\\+&%\$#_]*)?$", RegexOptions.CultureInvariant, matchTimeoutMilliseconds: 1000)] 
private static partial Regex _IsValidUrl(); 
public static bool ValidateUrl(string url) => _IsValidUrl ().IsMatch(url); 

Use the above code with a precompiled regex pattern for efficient URL validation. This will enhance both the readability and performance of your C# app. 

2. Regex.EnumerateSplits

A span-based input is allowed without allocation thanks to the new EnumerateSplits methods from the Regex class. 

ReadOnlySpan input = "Hello, world! How are you?"; 
foreach (Range r in Regex.EnumerateSplits(input, "[aeiou]")) 
{ 
    Console.WriteLine($"Split: \"{input[r]}\""); 
}

3. OrderedDictionary<TKey, TValue>

.NET 9 provides a new generic OrderedDictionary<TKey, TValue> collection.

OrderedDictionary orderDict = new() OrderedDictionary
{
[1] = ”Order No. 1”,
[2] = ”Order No. 2”,
[3] = ”Order No. 3”,
[4] = ”Order No. 4”
}
orderDict.Add(5, " Order No. 5");
orderDict.RemoveAt(0);
orderDict.Insert(0, 1, "New Order No. Inserted 1");
foreach (KeyValuePair item in orderDict)
{
Console.WriteLine($"{item.Key} : {item.Value}");
}
//Output :
//1 : New Order No. 1 Inserted
//2 : Order No. 2
//3 : Order No. 3
//4 : Order No. 4
//5 : Order No. 5

The code demonstrates how to create an OrderedDictionary, add, remove, and insert items, and then iterate through the collection to display its current state.

4. ReadOnlySet<T>

You can now create read-only views of sets with the new ReadOnlySet<T> from .NET 9. 

private readonly HashSet _set = new(); 
private readonly ReadOnlySet? _setWrapper; 
public ReadOnlySet Set => setWrapper ??= new(set);

Using this code, we create a read-only wrapper around the HashSet<int>. So that we don’t need to implement any modifications and can access the set’s elements safely. The set property makes sure that the read-only view is created once and then available for reuse. This will prevent the unnecessary creation of objects, resulting in enhanced performance. 

5. The allows ref struct in Libraries

C#13’s new “allows ref struct” constraint is utilized at several locations. It passes off the spans and other ref structs as input. 

public static string Create(int length, TState state, SpanAction action) where TState : allows ref struct;

6. Collection Lookups with Spans 

.NET 9 introduces new features performing span-based lookups in collections. 

//* Using Dictionary *//
var dictionary = new Dictionary
{
{ "key1", 1 },
{ "key2", 2 },
{ "key3", 3 }
};
var lookup = dictionary.GetAlternateLookup>();
var keys = " key1, key2, key3";
lookup["key4"] = 4; // Add new value
// .NET 9 SpanSplitEnumerator
foreach (Range range in keys.AsSpan().Split(','))
{
ReadOnlySpan key = keys.AsSpan(range).Trim();
// Get/Add/Remove from string key dictionary using ReadOnlySpan
int value = lookup[key];
Console.WriteLine(value);
}
//Output :
//1
//2
//3
//4

7. More Span-Based APIs

The .NET framework continuously adds new span-based APIs, enhancing string manipulation, file operations, and more.

ReadOnlySpan text = ...; 
File.WriteAllText(filePath, text); 
ReadOnlySpan text = "some arbitrary text"; 
return text.StartsWith('"') && text.EndsWith('"'); // false

8. Base64Url

.NET 9 comes with a whole new range of encoding and decoding methods with Base64Url. 

ReadOnlySpan bytes = ...; 
string encoded = Base64Url.EncodeToString(bytes);

9. SocketsHttpHandler by Default in HttpClientFactory

The default HttpClientFactory in .NET 9 utilizes the SocketsHttpHandler, which offers better configurability and connection management. 

10. TLS Resume with Client Certificates on Linux

In server-to-server scenarios, .NET 9 can prove to be efficient as it provides a feature supporting TLS resumes for mutually authenticated TLS connections on Linux. 

11. Introducing the Metrics Gauge Instrument

The level of background noise and other non-additive values can now be recorded in .NET 9, thanks to its System.Diagnostics.Metrics’s Gauge Instrument. 

Meter meter = new Meter("MeasurementLibrary.Sound"); 
Gauge gauge = meter.CreateGauge(name: "NoiseLevel", unit: "dB", description: "Background Noise Level"); 
gauge.Record(10, new TagList { "Room1", "dB" });

3. Conclusion

.NET 9 is new yet quite effective. You can use it to build various applications, ranging from web apps to AI-powered applications. This latest version of the .NET framework promises increased app performance and enhanced developer productivity. It’s an improvement to all of its successors by bringing the tools and updates that can shape the future of software development. 

Comments


Your comment is awaiting moderation.