This is the second part of our tour of the .NET 11 libraries (now generally available): JSON serialization, CBOR, networking and transport security, cryptography, configuration, validation, diagnostics and LINQ. For processes, compression and numerics see the first article of the series.
System.Text.Json
Unions
Starting in .NET 11, C# offers union types, for example public union Reading(int, string);. The serializer writes the active case directly, with no wrapper or $type discriminator: "hello" for a string, 42 for an integer, null for a union with no active case. On deserialization the case is selected from the JSON token kind; to tell two object cases apart, use JsonUnionAttribute with JsonUnionTypeStructuralClassifier, which picks by root-level property names. If zero or several cases match, a JsonException is thrown. For custom rules, derive from JsonTypeClassifierFactory and register it on one union, on JsonSerializerOptions.TypeClassifiers or on a source-generated context. JsonNumberHandlingAttribute is honored on unions and the generator no longer reports SYSLIB1227 for custom converters.
F# discriminated unions are serialized as strings (cases without fields) or objects with $type; that support is reflection-only and does not work with source generation, trimming or Native AOT.
JSON Lines, polymorphism and metadata
- JSONL: four
JsonSerializer.SerializeAsyncEnumerableoverloads target aStreamorPipeWriter; withtopLevelValues: truethey stream canonical JSON Lines (one compact value per line, LF-terminated, ignoringWriteIndented). - Closed hierarchies: with
InferClosedTypePolymorphism(on options, the generator orJsonPolymorphicAttribute) the serializer infers derived types and assigns deterministic discriminators; explicitJsonDerivedTypeAttributeregistrations take precedence. Open generic derived registrations such asDerived<>are supported too. - Source generation:
[JsonInclude]members with private, internal or protected accessors; inaccessible constructors marked withJsonConstructorAttribute;in,ref,outandref readonlyparameters; omitted init-only properties keep their initializer value. - GetTypeInfo<T>() and TryGetTypeInfo<T>(): return
JsonTypeInfo<T>without a cast. - Naming and ignoring:
JsonNamingPolicy.PascalCase,JsonNamingPolicyAttributeon a type or member,JsonIgnoreAttributewith a type-level condition (Alwaysis invalid at type level). - Converters and collections: built-in converters for
BFloat16,Decimal32,Decimal64,Decimal128; open generic converters;JsonExtensionDataonIReadOnlyDictionary;IReadOnlySet<T>as an array. - Utf8JsonWriter:
ResetwithJsonWriterOptionslets you reuse a writer.
Incremental CBOR
CborReader reads CBOR payloads delivered in chunks: construct it with isFinalBlock: false, check CborReaderState.NeedsMoreData and pass the next chunk to SlideData. It requires CborConformanceMode.Lax.
Networking and transport security
- TLS handshake: bounds-checking fixes in server-side
SslStream; on Linux, certificate-validation failures surface as standard TLS alerts as on Windows; Negotiate servers validate channel binding tokens on Unix as well. - Caller-driven TLS sessions (experimental):
TlsContext,TlsSession,TlsBufferSession,TlsSocketSession,TlsOperationStatus, diagnostic SYSLIB5007. - HTTP request compression:
GZipCompressedContent,BrotliCompressedContent,ZstandardCompressedContent. - SocketsHttpHandler:
ShouldEvictConnectionretires connections by age, endpoint and DNS changes;InitialHttp2MaxConcurrentStreamslimits the initial burst before the SETTINGS frame (minimum value 1). - DNS:
Dns.ResolveSrv,ResolveMx,ResolveTxt,ResolveCName,ResolvePtr,ResolveNs(and Async variants) withDnsResult<T>; theDnsResolverclass withDnsResolverOptionsaccepts custom DNS servers and now works on Linux too. - HTTP/2:
HttpClientautomatically downgrades to HTTP/1.1 when Windows authentication (NTLM/Negotiate) is required. - QUIC:
QuicStream.Priority(0 to 255, default 127) andDefaultPriority. - Also:
MediaTypeNames.Videoconstants; the HTTPopen_connectionsandactive_requestsmetrics become observable instruments (callMeterListener.RecordObservableInstruments()).
Cryptography
- X25519: the
X25519DiffieHellmanclass withGenerateKey()andDeriveRawSecretAgreement, plus PKCS#8, SPKI and PEM import/export. - FixedTimeEquals: a new overload compares a span against a single byte in constant time.
- AES Key Wrap: RFC 3394 (
EncryptKeyWrap,DecryptKeyWrap, multiples of 8 bytes) and RFC 5649 (EncryptKeyWrapPadded, any length), with array and span overloads. - Apple platforms:
AesGcmandChaCha20Poly1305avoid passing empty associated data to CryptoKit. - ML-KEM and HPKE (experimental):
CompositeMLKem(SYSLIB5006) combines post-quantum and classical KEMs;Hpke(SYSLIB5009) usesHpkeSuitewithSealandOpen. Suite availability depends on the platform. - CMS:
EnvelopedCmsencrypts with pure ML-KEM recipients, on non-Windows platforms only.
Configuration, options and validation
- Binding:
ConfigurationIgnoreAttributeopts properties out of binding; empty arrays bind to constructor parameters;PhysicalFilesWatcheris more reliable with missing directories and file systems without watching. - OptionsBuilder:
Validate<TValidator>()with anIValidateOptions<TOptions>registered in DI. - ChangeToken.OnChange:
Func<Task>overloads, noasync void. - HybridCache:
GetOrCreateAsyncoverloads with a mutable context for expiration and local cache size. - Async DataAnnotations:
AsyncValidationAttribute,IAsyncValidatableObject,Validator.ValidateObjectAsyncand friends; async options validation withIAsyncValidateOptionsandIAsyncStartupValidator(IStartupValidatoris obsolete);ValidationAttribute.FormatMessagefor localization.
Diagnostics and logging
- MemoryCache and OpenTelemetry: with
TrackStatistics = true, theMicrosoft.Extensions.Caching.Memory.MemoryCachemeter publishesdotnet.cache.requests(tagdotnet.cache.request.result),dotnet.cache.evictions,dotnet.cache.entriesanddotnet.cache.estimated_size; anIMeterFactorygives per-instance metrics. - Rule-based tracing:
AddTracingwithEnableTracing/DisableTracingfor sources and operations, drivable from configuration;ActivitySourceFactoryand an unsealedActivitySource. - Generic logging: generic
LoggerMessagemethods avoid boxing (theallows ref structanti-constraint is unsupported: SYSLIB1011).
LINQ
LeftJoin, RightJoin and the new FullJoin return tuples; Join and GroupJoin gain tuple-returning overloads with no result selector and an optional IEqualityComparer<T>. They are available on Enumerable, Queryable and AsyncEnumerable.
Sources
Comments (0)
No comments yet.