[ad_1]
Microsoft’s .NET 8 arrived November 14 with a plethora of recent options and enhancements. This text discusses the most important highlights in .NET 8, from my perspective, and consists of some code examples to get you began with the brand new options.
To make use of the code examples supplied on this article, you must have Visible Studio 2022 put in in your system. If you happen to don’t have already got a duplicate, you’ll be able to obtain Visible Studio 2022 right here.
Create a .NET Core console software mission in Visible Studio
First off, let’s create a .NET Core console software mission in Visible Studio. Assuming Visible Studio 2022 is put in in your system, comply with the steps outlined beneath to create a brand new .NET Core console software mission.
- Launch the Visible Studio IDE.
- Click on on “Create new mission.”
- Within the “Create new mission” window, choose “Console App (.NET Core)” from the record of templates displayed.
- Click on Subsequent.
- Within the “Configure your new mission” window, specify the identify and placement for the brand new mission.
- Click on Subsequent.
- Within the “Extra data” window proven subsequent, select “.NET 8.0” because the framework model you wish to use.
- Click on Create.
We’ll use this .NET Core console software mission to work with .NET 8’s greatest new options within the subsequent sections of this text.
Rubbish collector enhancements
The .NET rubbish collector now means that you can regulate reminiscence limits dynamically for cloud-native functions, particularly these working on Kubernetes. This function might be significantly useful in situations the place providers are hosted in a cloud atmosphere.
To leverage this function, name the RefreshMemoryLimit() API:
GC.RefreshMemoryLimit();
The next code snippet exhibits how one can refresh GC settings pertaining to the reminiscence restrict.
AppContext.SetData("GCHeapHardLimit", (ulong)100 * 1_024 * 1_024); GC.RefreshMemoryLimit();
JSON enhancements
A number of enhancements have been made to the JSON serialization and deserialization capabilities in .NET. This consists of assist for floating-point {hardware} and assist for brand spanking new numeric sorts like half structs.
Additional, when deserializing knowledge in earlier variations of .NET, any property in your JSON paytload that isn’t a POCO kind can be ignored. With .NET 8, you can also make all knowledge members accessible within the JSON payload.
To leverage this newly added performance, you will need to annotate your POCO kind with the System.Textual content.Json.Serialization.JsonUnmappedMemberHandlingAttribute attribute. That is proven within the code snippet given beneath.
[JsonUnmappedMemberHandling(JsonUnmappedMemberHandling.Disallow)] public class Worker { public int Employee_Id { get; set; } }
Now, if you happen to deserialize an occasion of the Worker class that specifies a member identify that isn’t part of the POCO kind, a JsonException might be thrown. For instance:
JsonSerializer.Deserialize<Worker> ("""{"Employee_Id" : 1, "Department_Id" : 1 }""");
Under is the exception message you’ll see when the code above is executed:
// JsonException : The JSON property 'Department_Id' couldn't be mapped to // any .NET member contained in kind 'Worker'.
Time abstraction
The newly added TimeProvider class and ITimer interface present time abstraction performance, thereby permitting you to mock time in take a look at scenerios. The time abstraction performance gives assist for the next:
- Create a brand new timer occasion
- Retrieve native time or UTC time
- Retrieve a timestamp for measuring efficiency
The TimeProvider summary class is designed in a approach that makes it appropriate for integration with mocking frameworks, offering strategies that facilitate seamless and complete mocking of all its points.
Cryptography enhancements
As cyber threats proliferate globally, new assist for SHA-3 assist makes .NET 8 functions safer, offering a substitute for SHA-2. Additionally in .NET 8, the RSA ephemeral operations have been moved to bcrypt.dll relatively than ncrypt.dll, avoiding the necessity to make a distant process name to lsass.exe.
The System.Safety.Cryptography.RandomNumberGenerator kind in .NET 8 introduces numerous strategies for utilizing randomness. These strategies are the GetItems() technique for randomly selecting objects from an enter set and the Shuffle() technique for decreasing coaching bias in machine studying.
Compression enhancements
Compressing recordsdata from a listing utilizing a stream is now attainable with out having to cache them. This enables direct reminiscence administration of the compression outcome. When disk house is proscribed, these APIs turn out to be helpful as a result of they eradicate the necessity for intermediate disk operations.
The System.IO.Compression namespace now includes a number of APIs as a part of the ZipFile class, as proven beneath.
namespace System.IO.Compression; public static partial class ZipFile { public static void CreateFromDirectory(string sourceDirectoryName, Stream vacation spot); public static void CreateFromDirectory(string sourceDirectoryName, Stream vacation spot, CompressionLevel compressionLevel, bool includeBaseDirectory); public static void CreateFromDirectory(string sourceDirectoryName, Stream vacation spot, CompressionLevel compressionLevel, bool includeBaseDirectory, Encoding? entryNameEncoding); public static void ExtractToDirectory(Stream supply, string destinationDirectoryName) { } public static void ExtractToDirectory(Stream supply, string destinationDirectoryName, bool overwriteFiles) { } public static void ExtractToDirectory(Stream supply, string destinationDirectoryName, Encoding? entryNameEncoding) { } public static void ExtractToDirectory(Stream supply, string destinationDirectoryName, Encoding? entryNameEncoding, bool overwriteFiles) { } }
Native AOT compilation enhancements
Help for native ahead-of-time (AOT) compilation was first launched in .NET 7. With .NET 8, Microsoft has added native AOT assist for x64 and Arm64 architectures on macOS, and has considerably lowered the dimensions of native AOT functions working on Linux.
Code technology enhancements
With .NET 8, Microsoft has additionally made quite a lot of enhancements to code technology and just-in-time (JIT) compilation:
- Enhanced efficiency of containerized functions in cloud-native environments
- SIMD enhancements for improved parallelization
- Profile-guided optimization (PGO) enhancements
- Dynamic PGO on by default
- Efficiency enhancements to Arm64 structure
- JIT enhancements for sooner code technology
Different efficiency enhancements
Efficiency is an space that Microsoft has centered on increasingly more in current releases of .NET. Listed below are another key efficiency enhancements in .NET 8.
Enhancements to Record<T>.AddRange(IEnumerable<T>)
The AddRange(IEnumerable<T>) has been refactored and enhanced for improved efficiency when the sequence isn’t a ICollection<T>.
Enhancements to Int32.ToString()
The Int32.ToString() technique has been enhanced for improved efficiency by caching strings values within the reminiscence.
Introduction of the System.Collections.Frozen namespace
System.Collections.Frozen introduces two new assortment courses, FrozenSet<T> and FrozenDictionary<T>. The phrase Frozen right here implies that the collections are immutable, i.e., you can not change them as soon as an occasion of those courses has been created. These new assortment courses allow you to carry out sooner lookups and enumerations utilizing strategies reminiscent of TryGetValue() and Incorporates().
The next code snippet illustrates how you should use a FrozenSet.
utilizing System.Collections.Frozen; Record<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();
Whenever you run the above piece of code, all the components of the integer array might be displayed within the console window.
Additional studying
Listed below are just a few on-line sources you’ll be able to try to get further details about .NET 8:
- Microsoft Study: The Microsoft Study web site has an online web page that covers all the new and enhanced options in .NET 8.
- GitHub documentation: You too can discover details about the brand new options in .NET 8 on the GitHub repository for .NET and .NET Core documentation.
- .NET web site: The official web site of Microsoft .NET has an online web page the place you’ll find extra particulars about .NET 8.
- .NET blogs and .NET neighborhood boards: You would possibly need to discover neighborhood blogs and boards the place builders share their experiences and insights concerning the options and updates in .NET. These platforms are nice for locating discussions on what’s new in a selected launch of .NET.
Microsoft’s .NET 8 launch is a serious leap ahead in constructing scalable, safe, strong, and performant functions. With the discharge of .NET 8, C# 12 was additionally made accessible. I’ll write a publish on the new options of C# 12 right here quickly.
Copyright © 2023 IDG Communications, Inc.
[ad_2]