What's new in .NET 9? Advanced .NET 9 Features

What's new in .NET 9? Advanced .NET 9 Features

05 Sep 2024
Beginner
65 Views
15 min read

.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
4ML.NET
5.NET Aspire
6ASP.NET Core
7.NET MAUI
8EF Core
9C# 13
10Windows 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() => ...;
}
When the app is trimmed using the following feature settings in the project file, Feature.IsSupported is set to false, and the Feature. Implementation code is eliminated.
<ItemGroup>
  <runtimehostconfigurationoption include="Feature.IsSupported" value="false" trim="true"></runtimehostconfigurationoption>
</ItemGroup>
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
{
    [FeatureGuard(typeof(RequiresDynamicCodeAttribute))]
    internal static bool IsSupported => RuntimeFeature.IsDynamicCodeSupported;

    [RequiresDynamicCode("Feature requires dynamic code support.")]
    internal static Implementation() => ...; // Uses dynamic code
}
Built with true, the call to Feature.Implementation() does not generate analyzer warnings IL3050 and Feature.When you publish, the implementation code is gone.

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

ML.NET is an open-source, cross-platform framework for integrating bespoke machine learning models into .NET applications. The most recent version, ML.NET 4.0, includes further tokenizer support for Tiktoken and models such as Llama and CodeGen.

5. .NET Aspire

.NET Aspire is an authoritative cloud-ready stack for developing observable, production-ready distributed apps. .NET Aspire is offered via a collection of NuGet packages that address certain cloud-native problems, and it is available in preview for.NET 9.

6. ASP.NET Core

ASP.NET Core contains enhancements to Blazor, SignalR, basic APIs, OpenAPI, and authentication and authorization.

1. .NET MAUI Blazor Hybrid and Web App solution template

A new solution template makes it easy to build .NET MAUI native and Blazor web client apps with the same UI. This template demonstrates how to build client apps that maximize code reuse and target Android, iOS, Mac, Windows, and the Web.
The key elements of this template include:
  • 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).
The sample code explains how to utilize dependency injection to offer distinct interface implementations for the Blazor Hybrid app and the Blazor Web App. To begin, install the.NET 9 SDK and the.NET MAUI workload, which includes the template.
 dotnet workload install maui
In a command shell, run the following command to create a solution from the project template.
 dotnet new maui-blazor-web
The template is also available for Visual Studio.

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

They've released a new API that simplifies the process of querying component states at runtime.
This API includes the following capabilities:
  • 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

The following improvements have been made to the default 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
    },
  },
});
The styling of the default reconnect UI has been updated.

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

MAUI (Multi-platform App UI) allows you to construct native apps from a single codebase. Here's an example.
 // 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

Entity Framework Core offers significant improvements to Azure Cosmos DB's NoSQL database provider. It also includes several processes for AOT compilation and pre-compiled queries, among other improvements.

9. C# 13

C# has long been a developer favorite, and with.NET 9 Preview 4, it's even better. You gain new language features that simplify and improve code readability. Here is a sneak peek:
 
// 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; }
}
Conclusion
.NET 9 Preview 4 is filled with improvements that will improve your development workflow. This framework is ideal for those seeking excellent performance, increased security, and robust tools. Also, consider our .NET Certification Training to better understand .net concepts.

FAQs

Q1. What is .NET 9 used for?

. NET is an open-source platform for building desktop, web, and mobile applications that can run natively on any operating system. The . NET system includes tools, libraries, and languages that support modern, scalable, and high-performance software development.

Q2. What is the difference between NET 8 and 9?

Expanded Native AOT Scenarios: Building on . NET 8's capabilities, . NET 9 extends native AOT to more complex application types. This expansion can lead to startup time improvements of up to 50% for certain application types, a crucial factor in serverless and containerized environments.

Q3. Will .net 9 be LTS?

The ninth version of . NET to be released this November will be the Standard Term Support version and will be supported for a year and a half.
Share Article

Live Classes Schedule

Our learn-by-building-project method enables you to build practical/coding experience that sticks. 95% of our learners say they have confidence and remember more when they learn by building real world projects.
ASP.NET Core Certification TrainingSep 21SAT, SUN
Filling Fast
09:30AM to 11:30AM (IST)
Get Details
ASP.NET Core Certification TrainingSep 29SAT, SUN
Filling Fast
08:30PM to 10:30PM (IST)
Get Details
ASP.NET Core ProjectOct 13SAT, SUN
Filling Fast
10:00AM to 12:00PM (IST)
Get Details

Can't find convenient schedule? Let us know

About Author
Shailendra Chauhan (Microsoft MVP, Founder & CEO at Scholarhat by DotNetTricks)

Shailendra Chauhan is the Founder and CEO at ScholarHat by DotNetTricks which is a brand when it comes to e-Learning. He provides training and consultation over an array of technologies like Cloud, .NET, Angular, React, Node, Microservices, Containers and Mobile Apps development. He has been awarded Microsoft MVP 8th time in a row (2016-2023). He has changed many lives with his writings and unique training programs. He has a number of most sought-after books to his name which has helped job aspirants in cracking tough interviews with ease.
Accept cookies & close this