21
NovWhat's new in .NET 9? Advanced .NET 9 Features
.NET Evolution
.NET Evolution has been a pillar of the software development industry, allowing developers to create various applications across multiple platforms. .NET has evolved into many versions from .Net 1.0 to .Net 10 till now. However, with the release of .NET 9, Microsoft continues to expand this strong framework, adding new features and improvements to meet the changing needs of developers.
Hence, In this .NET Tutorial, we’ll explore all about .NET 9 and What's new in .NET 9, the advanced features in .NET 9 that are set to redefine how developers build applications. So stay tuned with me and explore with me .NET 9.
What is new in .Net 9?
.NET 9, the successor to.NET 8, places a strong emphasis on cloud-native apps and performance. It will be supported for 18 months as an STS release. Designed to make development faster, easier, and more reliable. It works to improve efficiency, and security, and introduce new language features that make development easier.
Note. You can download the .NET 9 Version Easily from here |
So, As we are discussing, What is new in .Net 9? We will look into the following concepts which are newly updated in.NET9
No. | Different updated factors in.NET9 |
1 | .NET runtime |
2 | .NET libraries |
3 | .NET SDK |
4 | ML.NET |
5 | .NET Aspire |
6 | ASP.NET Core |
7 | .NET MAUI |
8 | EF Core |
9 | C# 13 |
10 | Windows Presentation Foundation |
1. .NET Runtime
The .NET 9 runtime features a new attribute model for feature switches that supports trimming. The new characteristics allow you to design feature switches that libraries can utilize to toggle different areas of functionality.Garbage collection contains a feature called dynamic adaptation to application size, which is employed by default instead of Server GC.The runtime also incorporates other speed enhancements, such as loop optimizations, inlining, and Arm64 vectorization and code creation.
New factors added in .NET Runtime
- Attribute model for feature switches with trimming support
- UnsafeAccessorAttribute supports generic parameters
- Garbage collection
- Performance improvements
1. Attribute model for feature switches with trimming support
In .NET 9 two new attributes allow you to design feature switches that the .NET libraries (and you) can utilize to toggle certain regions of functionality. If a feature is not supported, the unsupported (and consequently unneeded) features are eliminated during trimming or compilation using Native AOT, reducing the app size.
- FeatureSwitchDefinitionAttribute
- FeatureGuardAttribute
FeatureSwitchDefinitionAttributeis used to consider a feature-switch property as a constant when trimming, and dead code that is guarded by the switch can be deleted.
if (Feature.IsSupported)
Feature.Implementation();
public class Feature
{
[FeatureSwitchDefinition("Feature.IsSupported")]
internal static bool IsSupported => AppContext.TryGetSwitch("Feature.IsSupported", out bool isEnabled) ? isEnabled : true;
internal static Implementation() => ...;
}
<ItemGroup>
<runtimehostconfigurationoption include="Feature.IsSupported" value="false" trim="true"></runtimehostconfigurationoption>
</ItemGroup>
if (Feature.IsSupported)
Feature.Implementation();
public class Feature
{
[FeatureGuard(typeof(RequiresDynamicCodeAttribute))]
internal static bool IsSupported => RuntimeFeature.IsDynamicCodeSupported;
[RequiresDynamicCode("Feature requires dynamic code support.")]
internal static Implementation() => ...; // Uses dynamic code
}
2. UnsafeAccessorAttribute supports generic parameters
The UnsafeAccessorAttribute feature grants unsafe access to type members that the caller cannot access. This functionality was developed for.NET 8 but was deployed without support for generic parameters. .NET 9 now supports generic parameters for CoreCLR and native AOT scenarios. The code below provides an example of its use. using System.Runtime.CompilerServices;
public class Class<T>
{
private T? _field;
private void M<U>(T t, U u) { }
}
class Accessors<V>
{
[UnsafeAccessor(UnsafeAccessorKind.Field, Name = "_field")]
public extern static ref V GetSetPrivateField(Class<V> c);
[UnsafeAccessor(UnsafeAccessorKind.Method, Name = "M")]
public extern static void CallM<W>(Class<V> c, V v, W w);
}
internal class UnsafeAccessorExample
{
public void AccessGenericType(Class<int> c)
{
ref int f = ref Accessors<int>.GetSetPrivateField(c);
Accessors<int>.CallM<string>(c, 1, string.Empty);
}
}
2.NET libraries
- System.Text.Json includes new options for customizing the indentation character and size of written JSON. It also contains a new JsonSerializerOptions.A web singleton that allows for easier serialization with web defaults.
- In LINQ, the new methods CountBy and AggregateBy allow you to aggregate state by key without having to allocate intermediary groupings using GroupBy.
- For collection types, now you can use System.Collections.Generic.
- The PriorityQueue<TElement, TPriority> type now provides a Remove(TElement, TElement, TPriority, IEqualityComparer<TElement>) method for updating an item's priority in the queue.
- For cryptography, .NET 9 introduces a new one-shot hash method for the CryptographicOperations type. It also includes new classes that implement the KMAC algorithm.
- For reflection, the new PersistedAssemblyBuilder type allows you to preserve an emitted assembly. This new class also supports PDB, which allows you to emit symbol information and debug a created assembly.
- The TimeSpan class has new From* methods that allow you to build a TimeSpan object from an int (rather than a double). These strategies help to reduce errors caused by the inherent imprecision of floating-point calculations.
3. .NET SDK
- The .NET 9 SDK includes workload sets, in which all of your workloads remain at the same version until expressly changed.
- Unit testing includes improved MSBuild integration, allowing you to run tests in parallel.
- A new option for dotnet tool install allows users (rather than tool writers) to specify whether a tool may run on a newer.NET runtime version than the version it targets.
- NuGet security audits are performed on both direct and transitive package references by default.
- The terminal logger is now enabled by default, and its usability has been improved.
- For example, the total number of failures and warnings is now presented at the end of each build. New Microsoft Build script analyzers are now available.
4. ML.NET
5. .NET Aspire
6. ASP.NET Core
1. .NET MAUI Blazor Hybrid and Web App solution template
- The ability to select the Blazor interactive render mode for the web app.
- The required projects are automatically created, including a Blazor Web App (global Interactive Auto Rendering) and a.NET MAUI Blazor Hybrid application.
- To manage the Razor components in the UI, the generated projects make use of a shared Razor class library (RCL).
dotnet workload install maui
dotnet new maui-blazor-web
1. Static asset delivery optimization
MapStaticAssets is a new middleware that improves the delivery of static assets in any ASP.NET Core application, including Blazor apps.2. Detect rendering location, interactivity, and assigned render mode at runtime
- Determine the current execution location of the component.
- This can be especially beneficial for debugging and improving component performance.
- Check whether the component is executing in an interactive environment.
- This can be useful for components that exhibit varying behaviors depending on the interaction of their surroundings.
- Retrieve the component's assigned render mode.
- Understanding the render mode can help you optimize the rendering process and improve a component's overall performance.
3. Improved server-side reconnection experience
- When the user returns to an app with a severed circuit, reconnection is attempted immediately instead of waiting for the next reconnect interval.
- This enhances the user experience when accessing an app in a browser tab that has gone to sleep.
- When a reconnection attempt reaches the server but the server has already released the circuit, a page refresh is initiated immediately.
- This eliminates the need for the user to manually refresh the website if a successful reconnection is expected.
Blazor.start({
circuit: {
reconnectionOptions: {
retryIntervalMilliseconds: (previousAttempts, maxRetries) =>
previousAttempts >= maxRetries ? null : previousAttempts * 1000
},
},
});
4. Simpler authentication state serialization for Blazor Web Apps
- New APIs make it simpler to integrate authentication into an existing Blazor Web App.
- When you create a new Blazor Web App with Individual Account authentication and enable WebAssembly-based interactivity, a custom AuthenticationStateProvider is included in both the server and client projects.
- These providers transfer the user's authentication state to the browser. Authenticating on the server rather than the client allows the app to access authentication state during prerendering and before the Blazor WebAssembly runtime is loaded.
- The custom AuthenticationStateProvider implementations employ the Persistent Component State service (PersistentComponentState) to serialize the authentication state into HTML comments, which are then read back from WebAssembly to construct a new AuthenticationState.
7. NET MAUI
Develop with Xamarin and MAUI Updates
// Sample MAUI app code
using Microsoft.Maui;
using Microsoft.Maui.Controls;
namespace MyCompany
{
public class Company:Organization
{
public Company()
{
Employee= new NewEmployee();
}
}
}
8. EF Core
9. C# 13
// Example of new C# language feature in .NET 9
public class Person
{
public required string FirstName { get; init; } // 'required' keyword enforces assignment
public required string LastName { get; init; }
}