Dev

The best new features in Microsoft .NET 8


Microsoft’s .NET 8 arrived November 14 with a plethora of new features and enhancements. This article discusses the biggest highlights in .NET 8, from my point of view, and includes some code examples to get you started with the new features.

To use the code examples provided in this article, you should have Visual Studio 2022 installed in your system. If you don’t already have a copy, you can download Visual Studio 2022 here.

Create a .NET Core console application project in Visual Studio

First off, let’s create a .NET Core console application project in Visual Studio. Assuming Visual Studio 2022 is installed in your system, follow the steps outlined below to create a new .NET Core console application project.

  1. Launch the Visual Studio IDE.
  2. Click on “Create new project.”
  3. In the “Create new project” window, select “Console App (.NET Core)” from the list of templates displayed.
  4. Click Next.
  5. In the “Configure your new project” window, specify the name and location for the new project.
  6. Click Next.
  7. In the “Additional information” window shown next, choose “.NET 8.0” as the framework version you would like to use.
  8. Click Create.

We’ll use this .NET Core console application project to work with .NET 8’s best new features in the subsequent sections of this article.

Garbage collector improvements

The .NET garbage collector now allows you to adjust memory limits dynamically for cloud-native applications, especially those running on Kubernetes. This feature will be particularly helpful in scenarios where services are hosted in a cloud environment.

To leverage this feature, call the RefreshMemoryLimit() API:

GC.RefreshMemoryLimit();

The following code snippet shows how you can refresh GC settings pertaining to the memory limit.

AppContext.SetData("GCHeapHardLimit", (ulong)100 * 1_024 * 1_024);
GC.RefreshMemoryLimit();

JSON enhancements

Several enhancements have been made to the JSON serialization and deserialization functions in .NET. This includes support for floating-point hardware and support for new numeric types like half structs.

Further, when deserializing data in earlier versions of .NET, any property in your JSON paytload that isn’t a POCO type would be ignored. With .NET 8, you can make all data members available in the JSON payload.

To leverage this newly added functionality, you must annotate your POCO type with the System.Text.Json.Serialization.JsonUnmappedMemberHandlingAttribute attribute. This is shown in the code snippet given below.

[JsonUnmappedMemberHandling(JsonUnmappedMemberHandling.Disallow)]
public class Employee
{
     public int Employee_Id { get; set; }
}

Now, if you deserialize an instance of the Employee class that specifies a member name that is not a part of the POCO type, a JsonException will be thrown. For example:

JsonSerializer.Deserialize<Employee>
("""{"Employee_Id" : 1, "Department_Id" : 1 }""");

Below is the exception message you’ll see when the code above is executed:

// JsonException : The JSON property 'Department_Id' could not be mapped to 
// any .NET member contained in type 'Employee'.

Time abstraction

The newly added TimeProvider class and ITimer interface provide time abstraction functionality, thereby allowing you to mock time in test scenerios. The time abstraction functionality provides support for the following:

  • Create a new timer instance
  • Retrieve local time or UTC time
  • Retrieve a timestamp for measuring performance

The TimeProvider abstract class is designed in a way that makes it suitable for integration with mocking frameworks, providing methods that facilitate seamless and comprehensive mocking of all its aspects.

Cryptography enhancements

As cyber threats proliferate globally, new support for SHA-3 support makes .NET 8 applications more secure, providing an alternative to SHA-2. Also in .NET 8, the RSA ephemeral operations have been moved to bcrypt.dll rather than ncrypt.dll, avoiding the need to make a remote procedure call to lsass.exe. 

The System.Security.Cryptography.RandomNumberGenerator type in .NET 8 introduces various methods for using randomness. These methods are the GetItems() method for randomly choosing items from an input set and the Shuffle() method for reducing training bias in machine learning.

Compression enhancements

Compressing files from a directory using a stream is now possible without having to cache them. This allows direct memory management of the compression result. When disk space is limited, these APIs become useful because they eliminate the need for intermediate disk operations.

The System.IO.Compression namespace now comprises several APIs as part of the ZipFile class, as shown below.

namespace System.IO.Compression;
public static partial class ZipFile
{
    public static void CreateFromDirectory(string sourceDirectoryName, Stream destination);
    public static void CreateFromDirectory(string sourceDirectoryName, Stream destination, CompressionLevel compressionLevel, bool includeBaseDirectory);
    public static void CreateFromDirectory(string sourceDirectoryName, Stream destination, CompressionLevel compressionLevel, bool includeBaseDirectory, Encoding? entryNameEncoding);
    public static void ExtractToDirectory(Stream source, string destinationDirectoryName) { }
    public static void ExtractToDirectory(Stream source, string destinationDirectoryName, bool overwriteFiles) { }
    public static void ExtractToDirectory(Stream source, string destinationDirectoryName, Encoding? entryNameEncoding) { }
    public static void ExtractToDirectory(Stream source, string destinationDirectoryName, Encoding? entryNameEncoding, bool overwriteFiles) { }
}

Native AOT compilation improvements

Support for native ahead-of-time (AOT) compilation was first introduced in .NET 7. With .NET 8, Microsoft has added native AOT support for x64 and Arm64 architectures on macOS, and has significantly reduced the size of native AOT applications running on Linux.

Code generation improvements

With .NET 8, Microsoft has also made a number of improvements to code generation and just-in-time (JIT) compilation:

  • Enhanced performance of containerized applications in cloud-native environments
  • SIMD improvements for improved parallelization
  • Profile-guided optimization (PGO) improvements
  • Dynamic PGO on by default
  • Performance improvements to Arm64 architecture
  • JIT improvements for faster code generation

Other performance improvements

Performance is an area that Microsoft has focused on more and more in recent releases of .NET. Here are some other key performance improvements in .NET 8.

Improvements to List<T>.AddRange(IEnumerable<T>)

The AddRange(IEnumerable<T>) has been refactored and enhanced for improved performance when the sequence is not a ICollection<T>.

Improvements to Int32.ToString()

The Int32.ToString() method has been enhanced for improved performance by caching strings values in the memory.

Introduction of the System.Collections.Frozen namespace

System.Collections.Frozen introduces two new collection classes, FrozenSet<T> and FrozenDictionary<T>. The word Frozen here implies that the collections are immutable, i.e., you cannot change them once an instance of these classes has been created. These new collection classes enable you to perform faster lookups and enumerations using methods such as TryGetValue() and Contains().

The following code snippet illustrates how you can use a FrozenSet.

using System.Collections.Frozen;
List<int> numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9];
FrozenSet<int> frozenSet = numbers.ToFrozenSet();
foreach (int i in frozenSet)
    Console.WriteLine(i);
Console.ReadLine();

When you run the above piece of code, all of the elements of the integer array will be displayed in the console window. 

Further reading

Here are a few online resources you can check out to get additional information about .NET 8:

  • Microsoft Learn: The Microsoft Learn website has a web page that covers all of the new and enhanced features in .NET 8.
  • GitHub documentation: You can also find information about the new features in .NET 8 on the GitHub repository for .NET and .NET Core documentation.
  • .NET website: The official website of Microsoft .NET has a web page where you can find more details about .NET 8.
  • .NET blogs and .NET community forums: You might want to explore community blogs and forums where developers share their experiences and insights regarding the features and updates in .NET. These platforms are great for finding discussions on what’s new in a particular release of .NET.

Microsoft’s .NET 8 release is a major leap forward in building scalable, secure, robust, and performant applications. With the release of .NET 8, C# 12 was also made available. I’ll write a post on the new features of C# 12 here soon.

Copyright © 2023 IDG Communications, Inc.



READ SOURCE

This website uses cookies. By continuing to use this site, you accept our use of cookies.