In this article, we will discuss the .Net 8 new features with some code examples. The biggest highlight of .NET 8 though, is ASP.NET Core 8, which is a significant improvement to Microsoft's open-source framework for creating modern web applications. ASP.NET Core 8 is built on top of the .NET Core runtime and enables the development and execution of applications on Windows, Linux, and macOS. The Web API and MVC functionalities are combined in ASP.NET Core 8. This article provides various code examples while discussing what's new in ASP.NET 8.
You need Visual Studio 2022 installed on your computer to use the code examples in this article. Along with enormous improvements in efficiency and optimization, .Net 8 offers big-bet functionality. Let's examine the further improvements in this version.
Some of the top new key features in .Net 8 are listed below:
New Data Validation/ Annotation Attribute
dotnet publish and dotnet pack Release Mode
Randomness ( Random.GetItems<T>() & Random.Shuffle<T>())
Performance Improvements
Native AOT
Improvement in System.Text.Json serialization
Code Generation Improvements
.NET 8 DevOps Improvements
Let’s look at each of these key features in .Net 8.
New Data Validation/ Annotation Attribute:
The DataAnnotations namespace was created primarily for cloud-native service evaluation. The current DataAnnotations validators are mostly employed to validate user input, such as form fields. The new attributes, unlike configuration options, are intended to validate data rather than be provided by users. The RangeAttribute and RequiredAttribute types also got new properties in addition to the new attributes.
RequiredAttribute.DisallowAllDefaultValues: The attribute requires structs to test for inequality concerning their default values.
RangeAttribute.MinimumIsExclusive &RangeAttribute.MaximumIsExclusive:
Specifies whether the allowable range includes its boundaries or not.
DataAnnotations.LengthAttribute: Utilizes the Length attribute to define the minimum and maximum lengths for strings or collections. For example, the [Length(5, 100)] attribute mandates that a collection must include a minimum of 5 and a maximum of 100 pieces.
DataAnnotations.Base64StringAttribute: Validates a valid Base64 format.
DataAnnotations.AllowedValuesAttribute & DataAnnotations.DeniedValuesAttribute: Specifies accepted allow lists or not allowed deny lists. For instance: [AllowedValues("orange", "purple", "red")] or [DeniedValues("green", "yellow")].
Here is another example of the new features in .Net 8 can be understood by viewing the image below.
dotnet publish and dotnet pack Release Mode:
The dotnet publish and dotnet pack commands will now build and pack in Release mode, respectively. Before, it was in Debug mode while producing. The argument -p:PublishRelease must be set to false to generate in Debug mode. As you can see in the given below code.
dotnet publish -> /app/bin/Release/net8.0/app.dll
dotnet publish -p:PublishRelease=false -> /app/bin/Debug/net8.0/app.dll
The dotnet publish command is used to publish a .NET project for deployment. It compiles the project and its dependencies and generates the necessary files to run the application. The output directory can be specified using the -o or --output option.
By default, the output directory is <project_directory>/bin/Release/net8.0 for release builds and <project_directory>/bin/Debug/net8.0 for debug builds, where net8.0 represents the target framework. So, for the command dotnet publish, the output path would be /app/bin/Release/net8.0/app.dll.
The -p:PublishRelease=false is an additional argument that can be used to override the default behavior. In this case, it sets the PublishRelease property to false, indicating that a debug build should be published instead of a release build. Therefore, for the command dotnet publish -p:PublishRelease=false, the output path would be /app/bin/Debug/net8.0/app.dll.
Randomness ( Random.GetItems() & Random.Shuffle()) :
These days, AI programming is hugely popular. The urge to provide more arbitrary content also arose.
GetItems<T>():
The Random.GetItems and RandomNumberGenerator.GetItems methods are two new methods that are introduced, programmers can now choose a predetermined number of items at random from a given input collection. The example below demonstrates the usage of the System.Random.GetItems<T>() method using an instance obtained from the Random.Shared property to randomly insert 31 items into an array.
private static ReadOnlySpan<City> s_allCities = new[]
{
new City("New York", "USA"),
new City("London", "UK"),
new City("Paris", "France"),
new City("Tokyo", "Japan"),
new City("Sydney", "Australia"),
};
............
City[] selectedCities = Random.Shared.GetItems(s_allCities, 3);
foreach (City city in selectedCities)
{
Console.WriteLine(city.Name + ", " + city.Country);
}
Output:
Paris, France
Tokyo, Japan
Sydney, Australia
Shuffle<T>():
If you need to randomize the order of a span in your application, you can take advantage of two new methods: Random.Shuffle and RandomNumberGenerator.Shuffle. These techniques are especially useful when you want to change the order in which training and testing data are presented in machine learning to reduce the impact of training bias. By using these techniques, you can make sure that your dataset's first item is only occasionally used for training and its last item is only occasionally set aside for testing.
Here is an illustration of how to apply Shuffle<T>() to an array of MyType objects:
MyType[] trainingData = LoadTrainingData();
Random.Shared.Shuffle(trainingData);
IDataView sourceData = mlContext.Data.LoadFromEnumerable(trainingData);
DataOperationsCatalog.TrainTestData split = mlContext.Data.TrainTestSplit(sourceData);
model = chain.Fit(split.TrainSet);
IDataView predictions = model.Transform(split.TestSet);
In this example, we load some training data into an array of MyType objects and use Random.Shared to shuffle the order of the elements.
Performance Improvements:
To improve application performance, several new types have been added to .NET 8.
The System.Collections.Frozen namespace in .NET 8 includes the FrozenDictionary and FrozenSet collection types. After a collection has been created, these types are intended to stop modifications to the keys and values, enabling faster read operations like TryGetValue(). They are especially beneficial for collections that are initially populated and then persistent for a long-lasting service.
private static readonly FrozenDictionary<string, bool> dataConfiguration =
LoadConfigurationData().ToFrozenDictionary(optimizeForReads: true);
if (dataConfiguration.TryGetValue(key, out bool setting) && setting)
{
Process();
}
Buffers.IndexOfAnyValues is a new type in .NET 8 that is intended to be supplied to methods that look for the first instance of any value in a passed collection. The new overloads of methods like String.IndexOfAny and MemoryExtensions.IndexOfAny accepts an instance of the new type. A Buffers.IndexOfAnyValues instance is created with all the information required to optimize future searches already present.
Text.CompositeFormat is a new type in .NET 8 useful for optimizing format strings that aren't known at compile time (such as format strings loaded from a resource file). Even though it takes a little longer up front to complete duties like parsing the string, it prevents having to do the work every time the format string is used.
private static readonly CompositeFormat range = CompositeFormat.Parse(LoadRangeMessageResource());
static string GetMessage(int min, int max) =>
string.Format(CultureInfo.InvariantCulture, range, min, max);
Native AOT:
The native ahead-of-time (AOT) compilation functionality, which was first introduced in.NET 7, is improved in.NET 8. A self-contained version of an application created by publishing it as native AOT doesn't need a runtime because everything is contained in a single file.
.NET 8 now supports the x64 and Arm64 architectures on macOS in addition to the existing support for other platforms. As a result, programmers can now release their.NET applications as native AOT for macOS platforms.
The size of native AOT apps on Linux systems has greatly decreased as a result of recent enhancements.
Recent testing show that native AOT apps created with.NET 8 Preview 1 now consume up to 50% less space than those created with.NET 7.
The size of a "Hello World" app that was published with native AOT and included the entire.NET runtime is contrasted between the two versions in the table below:
Linux x64 (with -p:StripSymbols=true)
.NET 7 ➡ 3.76MB
.NET 8 ➡ 1.84 MB
Windows x64
.NET 7 ➡ 2.85 MB
.NET 8 ➡ 1.77 MB
Improvement in System.Text.Json serialization:
In more recent versions, System.Text.Json took the place of Newtonsoft.Json. The ABP Framework is now using System.Text.Json as well. The serialization and deserialization of objects have undergone a number of improvements. System.Text.Json is a built-in .NET library that provides JSON serialization and deserialization functionality. It allows developers to convert .NET objects to JSON data and vice versa.
This release also includes a number of enhancements that make the source generator faster and more dependable when used with ASP.NET Core in Native AOT projects. Additionally, the source generator will support in .NET 8 serializing types with required and init properties, which was already possible with reflection-based serialization.
Additionally, it is now able to customize serialization for members that aren't included in the JSON payload. Lastly, attributes from interface hierarchies, including those from the immediately implemented interface and its base interface, can now be serialized.
Code Generation Improvements:
Additionally, JIT (Just-In-Time) compilation and code generation have been improved in.NET 8 to boost performance and efficiency:
JIT (Just-In-Time) throughput improvements for faster code generation.
Arm64 architecture performance improvements.
Enhancements to profile-guided optimization (PGO) that permit better optimizations based on usage patterns of the application.
Improvements to SIMD (Single Instruction Multiple Data) for improved operation parallelization and vectorization.
Support for AVX-512 ISA extensions for newer CPUs' more effective floating-point operations.
Cloud-native upgrades for improved performance in situations with containers.
Performance-enhancing loop and general optimizations for frequently used code blocks.
These upgrades help developers in optimizing the operation of their .NET apps and reduce resources in cloud-native environments.
.NET 8 DevOps Improvements :
.NET container images :–
The functionality of.NET container images has also undergone some changes with NET 8. First off, the default Linux distribution in the container images is now Debian 12 (Bookworm).
The images also contain a non-root user to make them non-root capable. Add the line USER app at the end of your Dockerfile or a comparable command to your Kubernetes manifests to run as non-root.
In order to make port changes simpler, a new environment variable called ASPNETCORE_HTTP_PORTS is now available. The default port has also changed from 80 to 8080.
Compared to the structure demanded by ASPNETCORE_URLS, the syntax for the ASPNETCORE_HTTP_PORTS variable is simpler and takes a list of ports. It won't be feasible to run as someone other than root if you use one of these variables to change the port back to 80.
Use the following tag, which has the -preview suffix in the tag name for preview container images, to retrieve the.NET 8 Preview SDK:
docker run --rm -it mcr.microsoft.com/dotnet/sdk:8.0-preview
The Release candidate (RC) releases will no longer have the suffix -preview. Additionally, programmers can use .NET 8-enabled, .NET 8-chiseled Ubuntu images that have a reduced attack surface, no package management, no shell, and non-root capabilities. For developers seeking the benefits of computing in the appliance manner, these images are perfect.
Conclusion:
In general, .NET 8 delivers many innovative new features and enhancements to the .NET platform, facilitating the faster and more effective creation of high-performance, contemporary applications by designers. These are just a handful of the numerous additions and upgrades made in .NET 8. Additionally, developers should be aware that .NET 8 contains a number of performance enhancements and bug fixes that can help make their apps more reliable as well as fast.
Hope you enjoyed reading this article and found it useful. Please share your thoughts and recommendations in the comment section below.
Share This Post
Support Me