.NET 7 Features: What is New in .NET 7
Wednesday, November 22, 2023The Microsoft .NET ecosystem has grown steadily over the years, and each release adds new capabilities. Microsoft unveiled .NET 7 Preview 1 in honor of the platform’s 20th anniversary. The core .NET 7 features, such as a streamlined development process, increased productivity, and a unified set of .NET libraries and platforms, are carried over from .NET 6. Aside from that, we should expect progress in three key areas of .NET 7.
From the code generation to the new APIs to the performance improvements and bug fixes and beyond, the latest version improves every facet of the ecosystem. With these features, your hired .NET development company will be able to offer your business so much. Let’s start!
1. Top .NET 7 Features and Updates
.NET 7 recently introduced its new generation features and updates. Let’s discuss some of the finest ones below.
1.1 Faster, Lighter Apps (Native AOT)
Native AOT is one of the many enhancements and new features introduced by Microsoft .NET 7. After some time, Microsoft shifted its development efforts to prioritize its test Native AOT project. After many appeals, Microsoft has finally delivered a few changes to Native AOT.
Ahead-of-time (AOT) creates code at compile-time as opposed to run-time, which is how Native AOT works for those unfamiliar with the term.
Microsoft’s ReadyToRun (RTR) and Mono AOT (mobile and WASM) serve the same function, and both are available right now. Microsoft notes that while Native AOT may be an alternative to Mono AOT, it is not a replacement for WASM.
What sets apart Native AOT is that it creates code during compilation, but in Native. As stated by Microsoft, it primarily improves performance in the following areas:
- Initiation lag
- Memory usage
- Disk size
- Platforms with limited access
They also shared a benchmark showing that NativeAOT is 73% quicker to build and roughly half as light as ReadyToRun.
1.2 Observability
Microsoft also provides enhanced help for the cloud-native OpenTelemetry standard. .NET 7 now includes a tracestate feature that samplers can edit and should be provided to them.
- An ActivityContext object can be parsed and created using TryParse even if it was passed down from a parent activity on a distant device.
- To show if the Activity object has been halted, we can now use the new Activity.IsStopped() function.
- Featuring Activity.Current event transformation.
- Provide access to efficient enumerator methods for Activity attributes.
- Provide effective techniques for enumerating ActivityEvent and ActivityLink tags.
1.3 New APIs for Tar Archives
.NET 7 introduces support for tar archives.
The framework is installed as an additional component in the System.Formats.Tar. This API is available on several platforms and may be used to open, create, store, and extract tar files.
To access archives through filenames or streams, the library provides many overloads of methods like TarFile.CreateFromDirectory and Tar-File.ExtractToDirectory.
Below is a glimpse:
// Create a tar archive
TarFile.CreateFromDirectory(
sourceDirectoryName: "SourceDir/",
destinationFileName: "/ destinationFile.tar",
includeBaseDirectory: true
);
// Extract a tar archive
TarFile.ExtractToDirectory(
sourceFileName: "/destinationFile.tar",
destinationDirectoryName: "DestinationDir/",
overwriteFiles: false
);
You may also use the APIs to access an archive’s details, whether to read the items one by one or to add new ones.
The ability to combine stream-based compression algorithms, such as those included in the System.IO.Compression.GZipStream namespace, is particularly positive.
With the aforementioned features, such as being able to read and write entries of an archive file separately, this may be used to handle compressed archives like .tar.gz.
So, to clarify:
// Compressed tar file Creation
using FileStream compressedStream = File.OpenRead(" destinationFile.tar.gz");
using GZipStream tarDecompressor =new(compressedStream, CompressionMode.Decompress);
TarFile.ExtractToDirectory(
source: tarDecompressor,
destinationDirectoryName: " DestinationDir /",
overwriteFiles: true
);
1.4 .NET MAUI(Multi-Platform App UI)
By consolidating the Android, iOS, macOS, and Windows APIs into a single API, .NET MAUI makes it possible to create a single program that is native to many platforms. With .NET MAUI, you can create a unified brand experience across several platforms (Android, iOS, macOS, Windows, and Tizen) while still making use of the platform-specific features of each. Each system works as expected out of the box, without the need for extra widgets or style.
Developers have welcomed the streamlined process for developing .NET client apps in a single, unified project since .NET MAUI’s introduction. There are a growing number of .NET SDK tools and services available for .NET that make it easy to include capabilities like Azure Active Directory authentication, Bluetooth, printing, Near Field Communication (NFC), online/offline data syncing, and more into your apps. .NET 7 includes several enhancements to controls and layouts, as well as enhanced desktop capabilities and mobile Maps.
You’ve told us that certain native interactions would be extremely beneficial whether you’re employing Blazor hybrid controls or completely native controls with .NET MAUI for desktop. You can nowyour view using TooltipProperties to display useful text when an individual passes over a view. Text and a tooltip toggle on and off mechanically. The new PointerGesture allows you to apply hover and right-click gestures to any element, and the TapGesture now has masking properties.
A new Map control is available for viewing and annotating maps in native formats on Android, iOS, and iPadOS apps. Customers have used maps for anything from visualizing farming conditions to monitoring and presenting workouts to organizing trips. You can use the map to geocode addresses, latitude, and longitude. You can also use it to sketch freeform forms, pin locations, and add personalized markings.
Desktop computers also have a place for maps. The same Apple control is available for macOS, and our contribution to the .NET MAUI Community Toolkit is a browser-based version of the map control.
1.5 New Data Types
Several new data types have been introduced in .NET 7:
- DateOnly: Dates in the range of January 1, 0001 CE (Anno Domini) to December 31, 9999 CE (Common Era) are represented.
- TimeOnly: “Signifies a time of day between midnight and 23:59:59.9999999, as displayed on a clock.”
- Half: “Symbolizes a number with a floating-point accuracy of 0.5.”
- Int128
- UInt128
1.6 Cloud Native
The development experience on the way to creating cloud-native applications is the primary emphasis of .NET 7.
- Reduce the complexity of configuring secure authentication and permission.
- Boosting the application’s launch and execution times.
Orleans, a .NET framework for developing distributed applications, has received funding. Listed below are the most significant changes.
- Implement POCO grains.
- Serializers for grain persistence can be configured.
- Remove SMS provider.
- Create service abstractions that do not require a state.
- Add support for workflows in Orleans as a core feature.
- Make it easier for Orleans’s Azure users.
- Abstraction simplification for stream configurations.
- Upgrade asp .netcore with the New Orleans theme.
We are considering simplifying and improving the process of creating and releasing containerized .NET apps.
It has APIs for creating new instances of objects in the System.Composition.Holding structure. This resembles the performance of the classic user interfaces.
1.7 Built-In Containers Supports
When it comes to deploying applications to the cloud, many companies have found that using containers is the best option. .NET containers might help you create a more satisfying and efficient product. .Net publish now has native container support, letting you save your output to a container image instead of a directory.
Here are a few things to keep in mind:
- To successfully perform the publish command, Docker needs to be up and functioning.
- The Microsoft.NET.Build.Containers package must be referenced in the project.
1.8 New Regex Source Generator
The new Regex Source Generator function is ideal for dubbing and slicing, and it has all the effective benefits of the compiled engine in .NET 7 without the initial investment.
To start using it, you only need to make the enclosing type partial and declare a new partial function with the RegexGenerator property to return the optimized Regex object.
The source generator automatically executes the approach and refreshes it if you make any changes to your pattern or the optional parameters you provide.
Below is a glimpse:
Before:
public class RegexExample
{
public Regex regexp = new Regex(@"\d", RegexOptions.IgnoreCase);
public bool RegexGen(string str)
{
bool isMatched = regexp.IsMatch(str);
}
}
After:
// Make a partial class
public partial class RegexExample
{
// Add the attribute RegexGenerator (With pattern and options)
[RegexGenerator(@"\d", RegexOptions.IgnoreCase)]
//Partial method Declaration
public static partial Regex RegexMatchInput();
public bool RegexGen(string input)
{
// Partial method execution to make use of the developed engine.
bool isMatched = RegexMatchInput().IsMatch(input);
}
}
1.9 Blazor Hybrid Support
Current Blazor components may be assembled into a desktop program with the help of Blazor Hybrid Support by way of a webview control that has accessibility to all the hardware’s APIs. Web-based standards will be used to create desktop programs that can access the local file system or a camera.
1.10 Cryptography: Generating X.500 Names
This revision simplifies certificate management by adding a class that makes X.500 name parsing more clear. Most of the CertificateRequest functionality’s constructor parameters accept an X500DistingishedName type as entry for the certificate request subject.
Let’s demonstrate the code by way of an example.
request = new CertificateRequest($"CommonName=
{subjectName},OU=Test,O=""ABC Ltd.""", ...);
This works properly in most cases, but not when subjectName has special characters like commas or quotes.
To address this problem, the X500DistinguishedNameBuilder class was developed.
Since each technique only supports a single RDN, there is no room for confusion during parsing. Since then the RDN identities have grown.
X500DistinguishedNameBuilder nameBuilder = new();
nameBuilder.AddCommonName(subjectName);
nameBuilder.AddOrganizationalUnitName("Development");
nameBuilder.AddOrganizationName("ABC Ltd.");
request = new CertificateRequest(nameBuilder.Build(), ...);
1.11 Generic Math
The Generic Math library enables .NET programmers to use static APIs (such as operators) via generic code by combining the strength of generics with the recent addition called static virtuals in interfaces.
All the advantages of generics are at your disposal, and you may restrict the input to types that behave like numbers. This eliminates the requirement for a large number of almost similar implementations, which were previously necessary for supporting numerous kinds but are now unnecessary.
It also implies that your preferred operators are available to you in a variety of generic settings. In other words, the definition of static T Add(T left, T right) where T : INumber => left + right is now feasible.
public static TResult Multiply(IEnumerable values)
where T : INumber
where TResult : INumber
{
TResult result = TResult.Zero;
foreach (var value in values)
{
result *= TResult.Create(value);
}
return result;
}
public static TResult Factorial(IEnumerable values)
where T : INumber
where TResult : INumber {
TResult fact = Multiply(values);
return fact;
}
public static TResult FactorialByCount(IEnumerable values)
where T : INumber
where TResult : IFloatingPoint {
TResult factByCount = TResult.Zero;
if (values.Any())
{
TResult fact= Factorial(values);
factByCount = fact / TResult.Create(values.Count());
}
return factByCount ;
}
1.12 Easier Upgrading Existing .NET Apps
We’re all aware, and some of us have seen firsthand, that upgrading legacy apps to .NET 6 has not been an idyllic experience. Because of this, Microsoft is releasing improved upgrades for legacy software. Here are the key points:
- Better code-checking tools
- Better code-analyzing tools
- Compatibility checkers
Owing to Microsoft, this will all be included with the .NET Upgrade Assistant, which will make upgrading those apps much easier.
1.13 C# 11 Support
C# also receives a substantial version increase, as has been the case with each new .NET release in recent years. This year, C# has upgraded to the latest version 11, which adds some nifty new features and a sweet new syntax. Raw string literals and generic attribute support are two of C# 11’s most eye-catching new features.
1.14 Exposed Methods in Performance-Critical Scenarios
One key issue this new function addresses is the high number of launches seen in execution tests when utilizing enumeration interfaces. You may avoid making unnecessary allocations and gain fast access to the enumerated elements by making use of the accessible methods for enumerating attributes.
Take Microsoft for instance:
namespace System.Diagnostics
{
partial class Activity
{
public Enumerator<KeyValuePair> EnumerateTagObjects();
public Enumerator EnumerateLinks();
public Enumerator EnumerateEvents();
public struct Enumerator
{
public readonly Enumerator GetEnumerator();
public readonly ref T Current;
public bool MoveNext();
}
}
}
And the application would look like this:
Activity one = new Activity("Root");
one.SetTag("keyA", "valueA");
one.SetTag("keyB", "valueB");
foreach (ref readonly KeyValuePair act in one.EnumerateTagObjects())
{
Console.WriteLine($"{act.Key}, {act.Value}");
}
1.15 Microseconds and Nanoseconds in Date/Time Structures
The “tick” has a value of 100 ns and is the shortest time increment that might be utilized. The issue here is that you have to do all of your calculations in terms of a “tick” in order to obtain a result in microseconds or nanoseconds, which is not the most efficient method. Microsoft has announced that it will soon support adding microsecond and nanosecond values to the various date and time formats now in use.
Take Microsoft as an instance:
.NET 7 DateTime
namespace System {
public struct DateTime {
public DateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int microsecond);
public DateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int microsecond, System.DateTimeKind kind);
public DateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int microsecond, System.Globalization.Calendar calendar);
public int Microsecond { get; }
public int Nanosecond { get; }
public DateTime AddMicroseconds(double value);
}
}
.NET 7 TimeOnly
namespace System {
public struct TimeOnly {
public TimeOnly(int hour, int minute, int second, int millisecond, int microsecond);
public int Microsecond { get; }
public int Nanosecond { get; }
}
}
1.16 Raw String Literals
When working with raw string literals, you no longer have to use string concatenation to make content that spans many lines. There should be three double quotes at the beginning to denote the new options. The text does not require escape sequences to include blank space, fresh paragraphs, embedded quotes, and other special characters. In the source code, this greatly improves the readability of lengthy passages.
string longDemoMessage = """
This is a demo message.
This message has many lines.
This is line One.
This is line Two.
This is line Three.
This has "quoted text".
""";
You may also modify the curly brace count required to initiate and exit interpolation. You must use double curly brackets when the content begins with a single dollar sign. The number of curly brackets required to initiate interpolation increases by one for each additional dollar sign before the expression.
The series of $ symbols shows the number of interpolation brackets.
string name = "World";
string helloWorld = $"""Hello {name} !!! """;
1.17 On Stack Replacement (OSR)
With On Stack Replacement (OSR), the runtime can alter the methods’ on-the-fly execution without halting the current one, even if the method is still “on stack.” It’s a nice addition to the tiered compilation approach.
The runtime process utilizes tiered compilation and OSR to switch to more efficient versions of frequently invoked functions or functions with long-running loops during execution. This enables the runtime to initially JIT compile all methods quickly.
OSR accelerates rapid system boot. The fast JIT is now the default jitter for nearly all operations. Jittery programs like Avalonia’s “IL” spy reported a 25% reduction in initialization time and all of the TechEmpower benchmarks we keep an eye on indicate a 10-30% reduction in time for the initial response.
Since OSR enables long-running methods that lead to more optimized versions of mid-execution. It can also boost the speed of applications, especially those that employ Dynamic PGO. Activating OSR significantly increased performance on the Array2 microbenchmark.
1.18 Minimal APIs Improvements
The last .NET feature in our list is minimal API improvement. .NET 7 has come with some basic improvements in APIs and those upgrades are as below:
- Output Caching
- Upload Files in Minimal APIs
- Route Filter Handling
- Improvements to open API in minimal APIs
- Improved Dependency Injection
.NET developers can now rate-limit their applications and manage the rate of the dependencies that are called to create a better user experience, thanks to a new rate-limiting feature. In addition to this, some ASP.NET core improvements include Blazor Pages and nullable models for MVC.
2. Summary
As discussed in this article, .NET 7 incorporates performance improvements, C# 11 support, runtime, library, Native AOT, and MAUI/Blazor enhancements.
This major update enhances the .NET developer experience by enhancing the framework’s core features and making them easier to use for upcoming .NET projects. With .NET, you will have the freedom to create apps for every platform. The latest version of .NET has you covered up, whether you’re building mobile apps with .NET MAUI, energy-efficient apps for ARM64 devices, or top-tier cloud-native apps.
3. FAQs
What are the Benefits of .Net 7?
.NET 7 offers enhanced assistance, Native AOT, .NET multi-platform app UI, an analyzer, Blazor, command line performance, and more.
What is the Difference between .NET 6 and .NET 7?
.NET 6 has come with new built-in support for OpenAPI which makes it easy for the developers to generate API documentation and test the APIs while .NET 7 continues improving the OpenAPI support along with some new upgrades and features. Besides this, .NET 6 had introduced minimal APIs to enable the developers to create lightweight HTTP endpoints and now .NET 7 improves it and also comes with improved support for gPRC.
How do I Migrate from .NET 6 to .NET 7?
Here are the steps to migrate a .NET 6 application to .NET 7:
- Examine the .NET 7 release notes for new features and breaking changes.
- Update the project’s target framework in its project file from .NET 6 to .NET 7.
- Update all NuGet package references to their latest versions compatible with .NET 7.
- Test the application thoroughly and make necessary code adjustments to align with .NET 7’s features and optimizations.
Why is .NET 7 Faster?
.NET 7 is considered faster due to several performance improvements, including optimized just-in-time (JIT) compilation for quicker startup times and enhanced runtime for faster execution. It also reduces file system overhead, contributing to overall speed enhancements compared to previous versions.
Is .NET 7 Cross-Platform?
In the .NET framework, developers can get cross-platform app creation support by using .NET Core. With .NET 7, they can get new and improved cross-platform support as this version has come with the development of .NET MAUI and unified Base Class Library (BCL).
Comments