What's new in .NET 8
.NET 8 is the successor to .NET 7. It will be supported for three years as a long-term support (LTS) release. You can download .NET 8 here.
This article has been updated for .NET 8 Preview 2.
Important
- This information relates to a pre-release product that may be substantially modified before it's commercially released. Microsoft makes no warranties, express or implied, with respect to the information provided here.
- Much of the other .NET documentation on / has not yet been updated for .NET 8.
'dotnet publish' and 'dotnet pack'
Since the dotnet publish and dotnet pack commands are intended to produce production assets, they now produce Release assets by default.
The following output shows the different behavior between dotnet build and dotnet publish, and how you can revert to publishing Debug assets by setting the PublishRelease property to false.
/app# dotnet new console
/app# dotnet build
app -> /app/bin/Debug/net8.0/app.dll
/app# dotnet publish
app -> /app/bin/Release/net8.0/app.dll
app -> /app/bin/Release/net8.0/publish/
/app# dotnet publish -p:PublishRelease=false
app -> /app/bin/Debug/net8.0/app.dll
app -> /app/bin/Debug/net8.0/publish/
For more information, see 'dotnet pack' uses Release config and 'dotnet publish' uses Release config.
System.Text.Json serialization
Various improvements have been made to System.Text.Json serialization and deserialization functionality.
Performance and reliability enhancements of the source generator when used with ASP.NET Core in Native AOT apps.
The source generator now supports serializing types with
requiredandinitproperties. These were both already supported in reflection-based serialization.Customize handling of members that aren't in the JSON payload.
Support for serializing properties from interface hierarchies. The following code shows an example where the properties from both the immediately implemented interface and its base interface are serialized.
IDerived value = new DerivedImplement { Base = 0, Derived =1 }; JsonSerializer.Serialize(value); // {"Base":0,"Derived":1} public interface IBase { public int Base { get; set; } } public interface IDerived : IBase { public int Derived { get; set; } } public class DerivedImplement : IDerived { public int Base { get; set; } public int Derived { get; set; } }JsonNamingPolicyincludes new naming policies forsnake_case(with an underscore) andkebab-case(with a hyphen) property name conversions. Use these policies similarly to the existing JsonNamingPolicy.CamelCase policy:var options = new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.SnakeCaseLower }; JsonSerializer.Serialize(new { PropertyName = "value" }, options); // { "property_name" : "value" }JsonSerializerOptions.MakeReadOnly() gives you explicit control over when a
JsonSerializerOptionsinstance is frozen. (You can also check it with the IsReadOnly property.)
For more information about JSON serialization in general, see JSON serialization and deserialization in .NET.
Methods for working with randomness
The System.Random and System.Security.Cryptography.RandomNumberGenerator types introduce two new methods for working with randomness.
GetItems<T>()
The new System.Random.GetItems and System.Security.Cryptography.RandomNumberGenerator.GetItems methods let you randomly choose a specified number of items from an input set. The following example shows how to use System.Random.GetItems<T>() (on the instance provided by the Random.Shared property) to randomly insert 31 items into an array. This example could be used in a game of "Simon" where players must remember a sequence of colored buttons.
private static ReadOnlySpan<Button> s_allButtons = new[]
{
Button.Red,
Button.Green,
Button.Blue,
Button.Yellow,
};
...
Button[] thisRound = Random.Shared.GetItems(s_allButtons, 31);
// Rest of game goes here ...
Shuffle<T>()
The new Random.Shuffle and RandomNumberGenerator.Shuffle<T>(Span<T>) methods let you randomize the order of a span. These methods are useful for reducing training bias in machine learning (so the first thing isn't always training, and the last thing always test).
YourType[] 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);
// ...
Performance-focused types
.NET 8 introduces several new types aimed at improving app performance.
The new System.Collections.Frozen namespace includes the collection types FrozenDictionary<TKey,TValue> and FrozenSet<T>. These types don't allow any changes to keys and values once a collection created. That requirement allows faster read operations (for example,
TryGetValue()). These types are particularly useful for collections that are populated on first use and then persisted for the duration of a long-lived service, for example:private static readonly FrozenDictionary<string, bool> s_configurationData = LoadConfigurationData().ToFrozenDictionary(optimizeForReads: true); // ... if (s_configurationData.TryGetValue(key, out bool setting) && setting) { Process(); }The new System.Buffers.IndexOfAnyValues<T> type is designed to be passed to methods that look for the first occurrence of any value in the passed collection. For example, String.IndexOfAny(Char[]) looks for the first occurrence of any character in the specified array in the
stringit's called on. NET 8 adds new overloads of methods like String.IndexOfAny and MemoryExtensions.IndexOfAny that accept an instance of the new type. When you create an instance of System.Buffers.IndexOfAnyValues<T>, all the data that's necessary to optimize subsequent searches is derived at that time, meaning the work is done up front.The new System.Text.CompositeFormat type is useful for optimizing format strings that aren't known at compile time (for example, if the format string is loaded from a resource file). A little extra time is spent up front to do work such as parsing the string, but it saves the work from being done on each use.
private static readonly CompositeFormat s_rangeMessage = CompositeFormat.Parse(LoadRangeMessageResource()); // ... static string GetMessage(int min, int max) => string.Format(CultureInfo.InvariantCulture, s_rangeMessage, min, max);New System.IO.Hashing.XxHash3 and System.IO.Hashing.XxHash128 types provide implementations of the fast XXH3 and XXH128 hash algorithms.
System.Numerics and System.Runtime.Intrinsics
This section covers improvements to the System.Numerics and System.Runtime.Intrinsics namespaces.
- Vector256<T>, Matrix3x2, and Matrix4x4 have improved hardware acceleration on .NET 8. For example, Vector256<T> was reimplemented to internally be
2x Vector128<T>operations, where possible. This allows partial acceleration of some functions whenVector128.IsHardwareAccelerated == truebutVector256.IsHardwareAccelerated == false, such as on Arm64. - .NET 8 includes the initial implementation of Vector512<T>.
- Hardware intrinsics are now annotated with the
ConstExpectedattribute. This ensures that users are aware when the underlying hardware expects a constant and therefore when a non-constant value may unexpectedly hurt performance. - The Lerp(TSelf, TSelf, TSelf)
LerpAPI has been added to IFloatingPointIeee754<TSelf> and therefore tofloat(Single),double(Double), and Half. This API allows a linear interpolation between two values to be performed efficiently and correctly.
Data validation attributes
The System.ComponentModel.DataAnnotations namespace includes new data validation attributes intended for validation scenarios in cloud-native services. While the pre-existing DataAnnotations validators are geared towards typical UI data-entry validation, such as fields on a form, the new attributes are designed to validate non-user-entry data, such as configuration options. In addition to the new attributes, new properties were added to the RangeAttribute and RequiredAttribute types.
| New API | Description |
|---|---|
| RequiredAttribute.DisallowAllDefaultValues | Validates that structs don't equal their default values. |
| RangeAttribute.MinimumIsExclusive RangeAttribute.MaximumIsExclusive |
Specifies whether bounds are included in the allowable range. |
| System.ComponentModel.DataAnnotations.LengthAttribute | Specifies both lower and upper bounds for strings or collections. For example, [Length(10, 20)] requires at least 10 elements and at most 20 elements in a collection. |
| System.ComponentModel.DataAnnotations.Base64StringAttribute | Validates that a string is a valid Base64 representation. |
| System.ComponentModel.DataAnnotations.AllowedValuesAttribute System.ComponentModel.DataAnnotations.DeniedValuesAttribute |
Specify allow lists and deny lists, respectively. For example, [AllowedValues("apple", "banana", "mango")]. |
Introspection support for function pointers
Function pointers were introduced in .NET 5, however, the corresponding support for reflection wasn't added at that time. When using typeof or reflection on a function pointer, for example, typeof(delegate*<void>()) or FieldInfo.FieldType respectively, an IntPtr was returned. Starting in .NET 8, a System.Type object is returned instead. This type provides access to function pointer metadata, including the calling conventions, return type, and parameters.
Note
A function pointer instance, which is a physical address to a function, continues to be represented as an IntPtr. Only the reflection type has changed.
The new functionality is currently implemented only in the CoreCLR runtime and MetadataLoadContext.
New APIs have been added to System.Type, such as IsFunctionPointer, and to System.Reflection.PropertyInfo, System.Reflection.FieldInfo, and System.Reflection.ParameterInfo. The following code shows how to use some of the new APIs for reflection.
// Sample class that contains a function pointer field.
public unsafe class UClass
{
public delegate* unmanaged[Cdecl, SuppressGCTransition]<in int, void> _fp;
}
// ...
FieldInfo fieldInfo = typeof(UClass).GetField(nameof(UClass._fp));
// Obtain the function pointer type from a field.
Type fpType = fieldInfo.FieldType;
// New methods to determine if a type is a function pointer.
Console.WriteLine($"IsFunctionPointer: {fpType.IsFunctionPointer}");
Console.WriteLine($"IsUnmanagedFunctionPointer: {fpType.IsUnmanagedFunctionPointer}");
// New methods to obtain the return and parameter types.
Console.WriteLine($"Return type: {fpType.GetFunctionPointerReturnType()}");
foreach (Type parameterType in fpType.GetFunctionPointerParameterTypes())
{
Console.WriteLine($"Parameter type: {parameterType}");
}
// Access to custom modifiers and calling conventions requires a "modified type".
Type modifiedType = fieldInfo.GetModifiedFieldType();
// A modified type forwards most members to its underlying type.
Type normalType = modifiedType.UnderlyingSystemType;
// New method to obtain the calling conventions.
foreach (Type callConv in modifiedType.GetFunctionPointerCallingConventions())
{
Console.WriteLine($"Calling convention: {callConv}");
}
// New method to obtain the custom modifiers.
foreach (Type modreq in modifiedType.GetFunctionPointerParameterTypes()[0].GetRequiredCustomModifiers())
{
Console.WriteLine($"Required modifier for first parameter: {modreq}");
}
The previous example produces the following output:
IsFunctionPointer: True
IsUnmanagedFunctionPointer: True
Return type: System.Void
Parameter type: System.Int32&
Calling convention: System.Runtime.CompilerServices.CallConvSuppressGCTransition
Calling convention: System.Runtime.CompilerServices.CallConvCdecl
Required modifier for first parameter: System.Runtime.InteropServices.InAttribute
Native AOT
The option to publish as native AOT was first introduced in .NET 7. Publishing an app with native AOT creates a fully self-contained version of your app that doesn't need a runtime—everything is included in a single file.
.NET 8 adds support for the x64 and Arm64 architectures on macOS.
Also, the sizes of native AOT apps on Linux are now up to 50% smaller. The following table shows the size of a "Hello World" app published with native AOT that includes the entire .NET runtime on .NET 7 vs. .NET 8:
| Operating system | .NET 7 | .NET 8 Preview 1 |
|---|---|---|
Linux x64 (with -p:StripSymbols=true) |
3.76 MB | 1.84 MB |
| Windows x64 | 2.85 MB | 1.77 MB |
Code generation
.NET 8 includes improvements to code generation and just-in time (JIT) compilation:
- Arm64 performance improvements
- SIMD improvements
- Cloud-native improvements
- Profile-guided optimization (PGO) improvements
- Support for AVX-512 ISA extensions
- JIT throughput improvements
- Loop and general optimizations
.NET container images
The following changes have been made to .NET container images for .NET 8:
The container images now use Debian 12 (Bookworm). Debian is the default Linux distro in the .NET container images.
Images include a
non-rootuser. This user makes the imagesnon-rootcapable. To run asnon-root, add the following line at the end of your Dockerfile (or a similar instruction in your Kubernetes manifests):USER appThe default port also changed from port
80to8080. To support this change, a new environment variableASPNETCORE_HTTP_PORTSis available to make it easier to change ports. The variable accepts a list of ports, which is simpler than the format required byASPNETCORE_URLS. If you change the port back to port80using one of these variables, you can't run asnon-root.Preview container images tags now have a
-previewsuffix instead of just using the version number. For example, to pull the .NET 8 Preview SDK, use the following tag:docker run --rm -it mcr.microsoft.com/dotnet/sdk:8.0-previewThe
-previewsuffix will be removed for release candidate (RC) releases.Chiseled Ubuntu images are available for .NET 8. Chiseled images have a reduced attacked surface because they're ultra-small, have no package manager or shell, and are
non-root. This type of image is for developers that want the benefit of appliance-style computing. Chiseled images are published to the .NET nightly artifact registry.
Build your own .NET on Linux
In previous .NET versions, you could build .NET from source, but it required you to create a "source tarball" from the dotnet/installer repo commit that corresponded to a release. In .NET 8, that's no longer necessary and you can build .NET on Linux directly from the dotnet/dotnet repository. That repo uses dotnet/source-build to build .NET runtimes, tools, and SDKs. This is the same build that Red Hat and Canonical use to build .NET.
Building in a container is the easiest approach for most people, since the dotnet-buildtools/prereqs container images contain all the required dependencies. For more information, see the build instructions.
Minimum support baselines for Linux
The minimum support baselines for Linux have been updated for .NET 8:
- .NET will be built targeting Ubuntu 16.04, for all architectures. That's primarily important for defining the minimum
glibcversion for .NET 8. For example, .NET 8 will fail to even start on Ubuntu 14.04. - For Red Hat Enterprise Linux (RHEL), .NET supports RHEL 8+ and drops RHEL 7.
For more information, see Red Hat Enterprise Linux Family support.
See also
Feedback
Submit and view feedback for