You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
This issue is for teams to highlight work for the community that will release .NET 6 Preview 7.
To add content, use a new conversation entry. The entry should include the team name and feature title as the first line as shown in the template below.
## Team Name: Feature title
[link to the tracking issue or epic item for the work]
Tell the story of the feature and anything the community should pay particular attention
to be successful using the feature.
We added support for implicit namespace imports for C# projects to reduce the amount of boilerplate in project templates by reducing the using statements needed in each C# file.
Reacted by Weihan Li, expcat, Mo3in, Varorbc, Matěj Štágl, Steve, Leonardo Costa, C#, Alex, AraHaan and 20 more
Reacted by Uwe Keim and Halid Cisse
Reacted by Sophie L, Shivendra Pratap Singh, JohnDoeGeo, Jonas Arvidson, GuySerg, Abdul Rahman, hahyes and Uwe Keim
Reacted by Amichai Mantinband, Leonardo Costa, Max.Neo, Alex, AraHaan, Reilly Wood, Sophie L, Shivendra Pratap Singh, Jonas Arvidson, hahyes and 1 more
We added support to System.IO.Compression.ZipFile to capture Unix file permissions during create and set the file permissions when extracting zip archives on Unix. This allows for executable files to be "round tripped" through a zip archive, and it means you no longer have to modify the file permissions to make files executable anymore after extracting a zip archive. It also respects the read/write permissions for user, group, and other as well.
If a zip archive doesn't contain file permissions (because it was created on Windows, or using a tool which didn't capture the permissions, like an earlier version of .NET) extracted files get the default file permissions, just like any other newly created file. This behavior didn't change.
The Unix file permissions work with other zip archive tools as well, including:
We added new native memory allocation APIs exposed via System.Runtime.InteropServices.NativeMemory: dotnet/runtime#54006. These APIs represent equivalents to the malloc, free, realloc, and calloc C APIs and also includes APIs for doing aligned allocations.
Reacted by Boring3, Shivendra Pratap Singh, Yuuki Wesp, pedoc, C#, CryShana, kz-gonzalo-curbelo, Angelo Breuer, YohanS, Rafael CP and 2 more
Reacted by Boring3, Matěj Štágl, Dave Thalmann and Anira
Reacted by Boring3, Shivendra Pratap Singh, Dave Thalmann, Anira and Frederik Höft
Reacted by Boring3, Shivendra Pratap Singh, Anira and Frederik Höft
Reacted by Alex, AraHaan, Reilly Wood, Sergio Pedri, Boring3, Damian Romanowski, Shivendra Pratap Singh, Dan Moseley, GuySerg, Anira and 1 more
Serialization notifications and property ordering for System.Text.Json
These features make it much easier to customize the behavior of JSON objects. Previously, this functionality required implementing a custom converter.
Notifications for (de)serialization are useful for defaulting values and validation. To use them, implement one or more of the interfaces IJsonOnDeserialized, IJsonOnDeserializing, IJsonOnSerialized or IJsonOnSerializing from the System.Text.Json.Serialization namespace.
Here's an example that validates during both JsonSerializer.Serialize() and JsonSerializer.Deserialize() to ensure a FirstName property is not null.
publicclassPerson:IJsonOnDeserialized,IJsonOnSerializing{publicstringFirstName{get;set;}voidIJsonOnDeserialized.OnDeserialized()=>Validate();// Call after deserializationvoidIJsonOnSerializing.OnSerializing()=>Validate();// Call before serializationprivatevoidValidate(){if(FirstNameisnull){thrownewInvalidOperationException("The 'FirstName' property cannot be 'null'.");}}}
The order properties are serialized in can now be controlled by applying the System.Text.Json.Serialization.JsonPropertyOrderAttribute with an integer specifying the order. Smaller numbers are serialized first; properties that have no attribute have a default ordering value of 0. Previously, the order was determined by reflection order which is not deterministic.
Here's an example that specifies JSON should be serialized in the order Id, City, FirstName, LastName:
publicclassPerson{publicstringCity{get;set;}// No order defined (has the default ordering value of 0)[JsonPropertyOrder(1)]// Serialize after other properties that have default orderingpublicstringFirstName{get;set;}[JsonPropertyOrder(2)]// Serialize after FirstNamepublicstringLastName{get;set;}[JsonPropertyOrder(-1)]// Serialize before other properties that have default orderingpublicintId{get;set;}}
Reacted by Shivendra Pratap Singh, Jonas Arvidson, C#, Varorbc, Dan Moseley, Kevin Zhang, Maksym Koshovyi, Dave Thalmann, Uwe Keim, Joni Aromaa and 1 more
Introduced DistributedContextPropagator abstract class which determines if and how distributed context information is encoded and decoded as it traverses the network.
The encoding can be transported over any network protocol that supports string key-value pairs. For example, when using HTTP, each key value pair is an HTTP header.
DistributedContextPropagator inject values into and extracts values from carriers as string key/value pairs.
DistributedContextPropagatorpropagator=DistributedContextPropagator.Current;propagator.Inject(activity,carrier,(objecttheCarrier,stringfieldName,stringvalue)=>{// Extract the context from the activity then inject it to the carrier.});
Configure propagation with different propagator
// Set the current propagation behavior to not transmit any distributed context information in outbound network messages.DistributedContextPropagator.Current=DistributedContextPropagator.CreateNoOutputPropagator();
.NET Core has been supporting the Globalization Invariant Mode for a while. This mode used to support only ASCII range characters case mapping in operations like String.ToUpper, String.ToLower, and strings comparing and searching with Ignore Casing option. Now the full Unicode characters set case mapping fully supported in the Globalization Invariant Mode.
W^X (write xor execute) support for all platforms and architectures
The runtime now has a mode in which it doesn't create any memory pages that are writeable and executable at the same time. All executable memory is mapped as read-execute only. This was already supported on macOS ARM64 before preview 7, because it is not allowed to create memory mappings that are writeable and executable at the same time on that platform at all. Preview 7 adds that for all the remaining platform. On these platforms, executable code generation / modification is done via separate read-write memory mappings. This is true for both JITted code and runtime generated helpers. These mappings are created at virtual memory addresses that are different from the executable code address and exist only for a very brief period of time when the writing is performed. For example, JIT now generates code into a scratch buffer that is copied into the executable memory using a single memory copy function call after the whole method is jitted. And the writeable mapping lifetime spans only the time of the memory copy.
This new feature is disabled by default and it can be enabled by setting the environment variable DOTNET_EnableWriteXorExecute (or COMPlus_EnableWriteXorExecute) to 1. The reason is that there is a slightly worse startup performance (around 10% in the ASP.Net benchmark tests with R2R enabled) caused by this feature and we want to look into improving that (post .NET 6) before we enable it by default. However, the steady state performance was measured to be the same with and without the feature enabled. So for applications where the startup performance doesn't matter much, it might be interesting to try to enable it now.
Reacted by Manish Godse, Steve, OmariO, Sveinung, Matěj Štágl, Reilly Wood, Dan Moseley, AlgorithmsAreCool and Uwe Keim
Simplified call patterns for cryptographic operations
The .NET encryption and decryption routines were designed around streaming, with no real concession for when the payload is already in memory. The new Encrypt- and Decrypt- methods on SymmetricAlgorithm accelerate the already-in-memory case, and are intended to provide clarity to the caller and the code reviewer. Additionally, they support reading from and writing to spans.
Previous versions:
privatestaticbyte[]Decrypt(byte[]key,byte[]iv,byte[]ciphertext){using(Aesaes=Aes.Create()){aes.Key=key;aes.IV=iv;// These are the defaults, but let's set them anyways.aes.Padding=PaddingMode.PKCS7;aes.Mode=CipherMode.CBC;using(MemoryStreamdestination=newMemoryStream())using(ICryptoTransformtransform=aes.CreateDecryptor())using(CryptoStreamcryptoStream=newCryptoStream(destination,transform,CryptoStreamMode.Write)){cryptoStream.Write(ciphertext,0,ciphertext.Length);cryptoStream.FlushFinalBlock();returndestination.ToArray();}}}
With the new Encrypt- and Decrypt-methods only the key property is used from the SymmetricAlgorithm instance. The new DecryptCbc method does support choosing the padding algorithm, but PKCS#7 is used with CBC so often that it's a default argument. If you like the clarity, just specify it:
System.Text.Json.Nodes.JsonNode support for dynamic is removed.
As discussed in dotnet/runtime#53195, the "dynamic" feature in C# is considered somewhat stale and adding a dependency to a new JsonNode API (which was added in Preview 4) is not considered a good practice.
If a newer, more modern version of "dynamic" is introduced, this support will be reconsidered.
We updated .NET SDK templates to use latest C# language idioms when creating the project targeting .NET 6 framework.
The following language features will be used or enabled by default in the SDK-included project templates as applicable:
Top-level statements
Global using directives (via SDK driven defaults)
File-scoped namespaces
Target-typed new expressions
Nullable reference types
async Main
console template prior to .NET 6
using System;
namespace Company.ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello, World!");
}
}
}
.NET 6 console template
// See https://aka.ms/new-console-template for more information
Console.WriteLine("Hello, World!");
The users may encounter difficulty if the following scenarios which used to work before:
• Use a .NET 6 template and then change the target framework to previous version
• Use a .NET 6 template and then add different TFM to multi-target
More information on this breaking change is available here.
Reacted by Angelo Breuer, Reilly Wood, Weihan Li, Leonardo Costa, dimohy, YohanS, Alexandre Dias Simões, pedoc, Uwe Keim, Halid Cisse and 1 more
Reacted by Reilly Wood, Leonardo Costa and Uwe Keim
Reacted by i3ym and OpenByte
Reacted by Leonardo Costa, Amichai Mantinband, Dave Thalmann and Uwe Keim
namespaceSystem.Reflection{publicsealedclassNullabilityInfoContext{publicNullabilityInfoCreate(ParameterInfoparameterInfo);publicNullabilityInfoCreate(PropertyInfopropertyInfo);publicNullabilityInfoCreate(EventInfoeventInfo);publicNullabilityInfoCreate(FieldInfoparameterInfo);}publicsealedclassNullabilityInfo{publicTypeType{get;}// ReadState and WriteState could be different in case the member has nullability attribute affecting them// For example for a non null property [MaybeNull] attribute makes ReadState nullablepublicNullabilityStateReadState{get;}// For example for a nulllable property [DisallowNull] attribute makes WriteState not nullpublicNullabilityStateWriteState{get;}// if the member is an array, then the nullability of the array elements null otherwisepublicNullabilityInfo?ElementType{get;}// if the member has generic argument(s) then nullability of each argument, else empty arraypublicNullabilityInfo[]GenericTypeArguments{get;}}publicenumNullabilityState{Unknown,// Nullability not enabledNotNull,// Not nullable value or reference typeNullable// Nulable value or reference type}}
Usage
Getting top-level nullability information
privateNullabilityInfoContext_nullabilityContext=newNullabilityInfoContext();privatevoidDeserializePropertyValue(PropertyInfop,objectinstance,object?value){if(value==null){varnullabilityInfo=_nullabilityContext.Create(p);if(nullabilityInfo.WriteState!=NullabilityState.Nullable)thrownewMySerializerException($"Property '{p.GetType().Name}.{p.Name}'' cannot be set to null.");}p.SetValue(instance,value);}
This is powered by a new feature which allows static abstract members to be declared in interfaces. This enables interfaces to expose operators and other static methods, such as Parse or Create, and for those to be implemented by a derived type. Please see our associated blog post for more details!
Reacted by OmariO, C#, Angelo Breuer, dimohy, Steve, YohanS, Gilad Freidkin, i3ym, Maksym Koshovyi, Domingos Dellamonica Jr., PhD and 12 more
Reacted by Angelo Breuer, i3ym and Uwe Keim
Reacted by George, Angelo Breuer, Jacob McDowell, i3ym and Uwe Keim
Reacted by Denis Proshutinskii, Angelo Breuer, Adam Sitnik, i3ym, Dave Thalmann, Uwe Keim, Jumprocks and Eric Mutta
There are scenarios where customers want to integrate existing, "raw" JSON payloads when writing new JSON payloads with Utf8JsonWriter.
I have a blob which I think represents JSON content and which I want to envelope, and I need to make sure the envelope & its inner contents remain well-formed
I have a deliberate sequence of bytes I want to write out on the wire, and I know what I'm doing
Sample code:
JsonWriterOptionswriterOptions=new(){WriteIndented=true,};usingMemoryStreamms=new();usingUtfJsonWriterwriter=new(ms,writerOptions);writer.WriteStartObject();writer.WriteString("dataType","CalculationResults");writer.WriteStartArray("data");foreach(CalculationResultresultinresults){writer.WriteStartObject();writer.WriteString("measurement",result.Measurement);writer.WritePropertyName("value");// Write raw JSON numeric valuebyte[]formattedValue=FormatNumberValue(result.Value);writer.WriteRawValue(formattedValue,skipValidation:true);writer.WriteEndObject();}writer.WriteEndArray();writer.WriteEndObject();
In many scenarios, users need to serialize and deserialize JSON data to/from a stream in a synchronous manner. We've added new APIs on JsonSerializer to support this. Overloads that take source-generated content are also provided.
Reacted by SingleAccretion, Filip Navara, Tanner Gooding, Kunal Pathak, Angelo Breuer, Rich Lander, Clinton Ingram, dimohy, AlgorithmsAreCool, Sergio Pedri and 2 more
Activity
JunTaoLuo commentedon Jul 11, 2021
.NET SDK: C# Implicit Namespace Imports for C# Projects
Doc issue: dotnet/docs#25066
We added support for implicit namespace imports for C# projects to reduce the amount of boilerplate in project templates by reducing the using statements needed in each C# file.
For example, an empty web app looked like this:
but now it's simplified to:
eerhardt commentedon Jul 14, 2021
ZipFile Respects Unix File Permissions
We added support to
System.IO.Compression.ZipFileto capture Unix file permissions during create and set the file permissions when extracting zip archives on Unix. This allows for executable files to be "round tripped" through a zip archive, and it means you no longer have to modify the file permissions to make files executable anymore after extracting a zip archive. It also respects the read/write permissions for user, group, and other as well.If a zip archive doesn't contain file permissions (because it was created on Windows, or using a tool which didn't capture the permissions, like an earlier version of .NET) extracted files get the default file permissions, just like any other newly created file. This behavior didn't change.
The Unix file permissions work with other zip archive tools as well, including:
tannergooding commentedon Jul 15, 2021
NativeMemory
We added new native memory allocation APIs exposed via
System.Runtime.InteropServices.NativeMemory: dotnet/runtime#54006. These APIs represent equivalents to themalloc,free,realloc, andcallocC APIs and also includes APIs for doing aligned allocations.steveharter commentedon Jul 21, 2021
Serialization notifications and property ordering for System.Text.Json
These features make it much easier to customize the behavior of JSON objects. Previously, this functionality required implementing a custom converter.
Notifications for (de)serialization are useful for defaulting values and validation. To use them, implement one or more of the interfaces
IJsonOnDeserialized,IJsonOnDeserializing,IJsonOnSerializedorIJsonOnSerializingfrom theSystem.Text.Json.Serializationnamespace.Here's an example that validates during both
JsonSerializer.Serialize()andJsonSerializer.Deserialize()to ensure aFirstNameproperty is notnull.The order properties are serialized in can now be controlled by applying the
System.Text.Json.Serialization.JsonPropertyOrderAttributewith an integer specifying the order. Smaller numbers are serialized first; properties that have no attribute have a default ordering value of 0. Previously, the order was determined by reflection order which is not deterministic.Here's an example that specifies JSON should be serialized in the order
Id, City, FirstName, LastName:danmoseley commentedon Jul 22, 2021
@tannergooding should there be something about dotnet/runtime#55776 here? although it's a little special.
tannergooding commentedon Jul 22, 2021
Yes. I will be adding it and working on the related blog post when I get back from vacation.
danmoseley commentedon Jul 22, 2021
Oops, didn't realize you were on vacation. 😺
tarekgh commentedon Jul 26, 2021
Introducing System.Diagnostics Propagators
Developers will be able to control how distributed tracing information is propagated
Introduced
DistributedContextPropagatorabstract class which determines if and how distributed context information is encoded and decoded as it traverses the network.The encoding can be transported over any network protocol that supports string key-value pairs. For example, when using HTTP, each key value pair is an HTTP header.
DistributedContextPropagator inject values into and extracts values from carriers as string key/value pairs.
Configure propagation with different propagator
CC @noahfalk @shirhatti
tarekgh commentedon Jul 26, 2021
Full Case Mapping Support in Globalization Invariant Mode
Doc
.NET Core has been supporting the Globalization Invariant Mode for a while. This mode used to support only ASCII range characters case mapping in operations like
String.ToUpper,String.ToLower, and strings comparing and searching with Ignore Casing option. Now the full Unicode characters set case mapping fully supported in the Globalization Invariant Mode.danmoseley commentedon Jul 26, 2021
When mentioning the improvement to Globalization Invariant Mode above it might be an opportunity to note the breaking change dotnet/docs#24849
tarekgh commentedon Jul 26, 2021
@danmoseley the doc I linked is the published breaking change doc.
danmoseley commentedon Jul 26, 2021
@tarekgh ah my bad, I had forgotten they were both in the same breaking change doc.
janvorli commentedon Jul 28, 2021
W^X (write xor execute) support for all platforms and architectures
The runtime now has a mode in which it doesn't create any memory pages that are writeable and executable at the same time. All executable memory is mapped as read-execute only. This was already supported on macOS ARM64 before preview 7, because it is not allowed to create memory mappings that are writeable and executable at the same time on that platform at all. Preview 7 adds that for all the remaining platform. On these platforms, executable code generation / modification is done via separate read-write memory mappings. This is true for both JITted code and runtime generated helpers. These mappings are created at virtual memory addresses that are different from the executable code address and exist only for a very brief period of time when the writing is performed. For example, JIT now generates code into a scratch buffer that is copied into the executable memory using a single memory copy function call after the whole method is jitted. And the writeable mapping lifetime spans only the time of the memory copy.
This new feature is disabled by default and it can be enabled by setting the environment variable
DOTNET_EnableWriteXorExecute(orCOMPlus_EnableWriteXorExecute) to 1. The reason is that there is a slightly worse startup performance (around 10% in the ASP.Net benchmark tests with R2R enabled) caused by this feature and we want to look into improving that (post .NET 6) before we enable it by default. However, the steady state performance was measured to be the same with and without the feature enabled. So for applications where the startup performance doesn't matter much, it might be interesting to try to enable it now.bartonjs commentedon Jul 28, 2021
Simplified call patterns for cryptographic operations
The .NET encryption and decryption routines were designed around streaming, with no real concession for when the payload is already in memory. The new Encrypt- and Decrypt- methods on
SymmetricAlgorithmaccelerate the already-in-memory case, and are intended to provide clarity to the caller and the code reviewer. Additionally, they support reading from and writing to spans.Previous versions:
With the new simplified methods:
With the new Encrypt- and Decrypt-methods only the key property is used from the SymmetricAlgorithm instance. The new DecryptCbc method does support choosing the padding algorithm, but PKCS#7 is used with CBC so often that it's a default argument. If you like the clarity, just specify it:
steveharter commentedon Jul 28, 2021
System.Text.Json.Nodes.JsonNode support for
dynamicis removed.As discussed in dotnet/runtime#53195, the "dynamic" feature in C# is considered somewhat stale and adding a dependency to a new
JsonNodeAPI (which was added in Preview 4) is not considered a good practice.If a newer, more modern version of "dynamic" is introduced, this support will be reconsidered.
See also the breaking change issue .
Preview 4-6 behavior
The "dynamic" keyword could be used to get and set properties on the new
JsonObjectclass such as:Preview 7 behavior
The property name must be specified as a string, and "dynamic" not used:
vlada-shubina commentedon Jul 30, 2021
.NET 6 C# project templates use latest language idioms
dotnet/templating#3359
We updated .NET SDK templates to use latest C# language idioms when creating the project targeting .NET 6 framework.
The following language features will be used or enabled by default in the SDK-included project templates as applicable:
consoletemplate prior to .NET 6.NET 6
consoletemplateThe users may encounter difficulty if the following scenarios which used to work before:
• Use a .NET 6 template and then change the target framework to previous version
• Use a .NET 6 template and then add different TFM to multi-target
More information on this breaking change is available here.
buyaa-n commentedon Aug 3, 2021
Added APIs for exposing nullability information from reflection
Runtime Issue: dotnet/runtime#29723
API shape
Usage
Getting top-level nullability information
Getting nested nullability information
tannergooding commentedon Aug 5, 2021
Generic Math
We are previewing (as in they will not ship as "stable" with .NET 6) several new interfaces which enable operators to be used with generics:
This is powered by a new feature which allows
static abstractmembers to be declared in interfaces. This enables interfaces to expose operators and other static methods, such asParseorCreate, and for those to be implemented by a derived type. Please see our associated blog post for more details!layomia commentedon Aug 6, 2021
System.Text.Json
Utf8JsonWriter "write raw" APIs (dotnet/runtime#1784)
There are scenarios where customers want to integrate existing, "raw" JSON payloads when writing new JSON payloads with Utf8JsonWriter.
Sample code:
New synchronous stream overloads on
JsonSerializer(dotnet/runtime#1574)In many scenarios, users need to serialize and deserialize JSON data to/from a stream in a synchronous manner. We've added new APIs on
JsonSerializerto support this. Overloads that take source-generated content are also provided.JulieLeeMSFT commentedon Aug 10, 2021
CodeGen
Community PRs
From @SingleAccretion:
CAST(int <- long)on 32 bit targets runtime#53040cgt.un(op, 0)asNE(op, 0)runtime#54539Dynamic PGO dotnet/runtime#43618
LSRA dotnet/runtime#43318
Loop Optimization
Structs
TryTransformStoreObjAsStoreIndoptimization. runtime#55727Optimizations
danmoseley commentedon Aug 10, 2021
Gosh @SingleAccretion did a lot!
filipnavara commentedon Aug 10, 2021
One of them is listed twice but still hell of a job!
kunalspathak commentedon Aug 10, 2021
@EgorBo - Feel free to add some performance improvement graphs for dynamic PGO/inline changes.
JulieLeeMSFT commentedon Aug 11, 2021
Thanks for catching it. Deleted the line.
[-]What's new in .NET 6 Preview 7 [WIP][/-][+]What's new in .NET 6 Preview 7[/+]