loading experience

.NET

Guide to .NET 11: CLR, libraries, SDK, C# 15, EF Core, ASP.NET Core and .NET MAUI

.NET 11 is generally available (GA). This guide gathers in a single path everything that changes: the CLR and Runtime Async, the libraries, the SDK and tooling, C# 15, EF Core 11, ASP.NET Core 11 and .NET MAUI with its architecture. Each section is a complete article, with the official Microsoft sources.

Where to download it

In this guide

  1. .NET 11 GA: overview of what's new and where to download it
  2. .NET 11: Runtime Async, async built into the runtime
  3. .NET 11: JIT, NativeAOT, WebAssembly and hardware requirements
  4. .NET 11 libraries: processes, compression, numbers and in-memory streams
  5. .NET 11 libraries: JSON, networking, cryptography, validation and diagnostics
  6. .NET 11 SDK and CLI tooling: everything new and how to upgrade
  7. What's new in C# 15: unions, closed and more
  8. What's new in EF Core 11: complex types, vectors, Cosmos
  9. ASP.NET Core 11: everything that's new
  10. What's new in .NET MAUI for .NET 11
  11. .NET MAUI architecture: layers, handlers and single project

.NET 11 GA: overview of what's new and where to download it

.NET 11 is generally available (GA): the official "What's new in .NET 11" page was updated for the GA release and links to the download. This overview summarizes the main changes in the runtime, libraries, SDK, C# 15, ASP.NET Core, EF Core and .NET MAUI, along with the official links to install it and the requirements to check.

Runtime

  • More modern minimum hardware requirements on x86/x64 and Arm64.
  • Runtime Async (runtime-native async): cleaner stack traces and lower overhead. Projects targeting net11.0 no longer need EnablePreviewFeatures, and the runtime libraries themselves are compiled with runtime-async=on.
  • JIT improvements: bounds check elimination, devirtualization, switch expression folding, constant-folded SequenceEqual, new Arm SVE2 and AVX-VNNI-512 intrinsics, and a faster Math.BigMul on x64.
  • CoreCLR on WebAssembly now runs the libraries test suite end to end.
  • In-process crash reports (mobile, Linux and macOS), faster NativeAOT interface dispatch, SIMD lane construction and composition APIs, and hardware FP16 instructions for Half.

We cover the runtime in two dedicated articles: one on Runtime Async and one on the JIT, NativeAOT and platforms.

Libraries

  • Expanded Process APIs: run-and-capture helpers, fire-and-forget launches, ProcessStartInfo.StartSuspended, and Process.Signal(PosixSignal).
  • Compression: Zstandard in System.IO.Compression, CRC32 validation of ZIP entries, and improved Base64 APIs.
  • Numerics: IEEE 754 decimal types (Decimal32, Decimal64, Decimal128) and a generic Complex<T>.
  • System.Text.Json: C# and F# union support, JSON Lines output, and more control over polymorphism, source generation and naming.
  • Networking and security: HTTP request-body compression, typed DNS APIs (DnsResolver), TLS handshake hardening, X25519DiffieHellman, and experimental ML-KEM and HPKE APIs.
  • LINQ: FullJoin and tuple-returning Join/GroupJoin overloads.
  • Asynchronous validation in DataAnnotations and Microsoft.Extensions.Options, OpenTelemetry metrics for MemoryCache, and four new Stream types that wrap in-memory data without copying.

SDK

  • Smaller installers on Linux and macOS, and solution filters (.slnf) that can be created and edited from dotnet sln.
  • File-based apps: #:include, dotnet format support and Native AOT build-output reuse.
  • dotnet run -e to pass environment variables; dotnet watch with Aspire integration, automatic crash recovery and device selection for MAUI.
  • NativeAOT CLI and MSBuild server enabled by default; CLI telemetry based on OpenTelemetry.
  • dotnet test: new options, support for Android, iOS, macOS and Mac Catalyst test projects, and xUnit v3 (with Microsoft.Testing.Platform) and NUnit templates.
  • Containers: multi-architecture builds with Podman, a preference for native local runtimes, and reproducible digests through SOURCE_DATE_EPOCH.

C# 15

C# 15 is the default language version for projects that target .NET 11. The listed features are: collection expression arguments, union types, closed hierarchies, extension indexers, labeled break and continue, and memory-safety changes.

ASP.NET Core, EF Core and MAUI at a glance

  • ASP.NET Core: the what's-new page describes, among other things, the new Blazor DisplayName<TValue> component, which shows property names from the [Display] and [DisplayName] attributes, and the unified Blazor.start options format for the Blazor Server and WebAssembly scripts.
  • EF Core 11: requires the .NET 11 SDK and runtime, and does not run on earlier .NET versions or on .NET Framework. Among the changes, complex types and JSON columns now work with TPT and TPC inheritance.
  • .NET MAUI: the focus is product quality. CoreCLR is the default runtime on all MAUI platforms, with NativeAOT as an opt-in publishing alternative. Highlights include test project templates for Android, iOS, tvOS, macOS and Mac Catalyst, LongPressGestureRecognizer, passkeys (WebAuthn/FIDO2) and dark-mode splash screens.

Where to download it

These are official links, and we checked each one (HTTP 200):

Requirements and upgrading

  • Hardware: on x86/x64 the baseline moves from x86-64-v1 to x86-64-v2 on every OS; on Arm64, Windows now requires LSE, while Apple and Linux keep their baseline. On hardware that is too old, .NET fails to start and may print "The current CPU is missing one or more of the baseline instruction sets".
  • EF Core 11: you need the .NET 11 SDK to build and the .NET 11 runtime to run.
  • Breaking changes: the official documentation points to a dedicated "Breaking changes in .NET 11" page, worth reading before you migrate. For example, advisory file locking is now disabled by default on iOS and tvOS.
  • MAUI: in .NET 11 it ships as a .NET workload plus NuGet packages, so you can pin projects to specific versions. The MAUI support policy differs from the .NET one because it depends on external components such as Xcode or the Android SDK tools.

Sources


.NET 11: Runtime Async, async built into the runtime

Runtime Async (runtime-native async, "Runtime Async V2") is one of the most significant changes in the .NET 11 runtime. Instead of the compiler emitting classes that implement a state machine, the runtime itself tracks suspension and resumption of asynchronous execution. According to the official documentation, the result is cleaner stack traces, better debuggability and lower overhead.

How to enable it

In a project that targets net11.0, add this property to the project file:

<PropertyGroup>
  <Features>runtime-async=on</Features>
</PropertyGroup>
  • A net11.0 project no longer requires EnablePreviewFeatures.
  • The runtime libraries are compiled with runtime-async=on and no longer contain compiler-generated state machines. That makes it possible to migrate an entire app (with only library dependencies) to the new model, and it gives broad functional and performance validation of the feature. The product team welcomes reports, positive or negative, on throughput and library size.
  • The DOTNET_RuntimeAsync and UNSUPPORTED_RuntimeAsync environment variables have been removed. To opt out per project, set <UseRuntimeAsync>false</UseRuntimeAsync> in the project file.

Cleaner live stack traces

The most visible improvement is in live stack traces: what profilers, debuggers and new StackTrace() see during execution. With compiler-generated async, each async method produces several frames of infrastructure; with Runtime Async, the actual methods appear directly on the stack. In the official sample:

await OuterAsync();
static async Task OuterAsync()
{
    await Task.CompletedTask;
    await MiddleAsync();
}
static async Task MiddleAsync()
{
    await Task.CompletedTask;
    await InnerAsync();
}
static async Task InnerAsync()
{
    await Task.CompletedTask;
    Console.WriteLine(new StackTrace(fNeedFileInfo: true));
}
  • Without runtime-async: 13 frames, with the state-machine infrastructure (AsyncMethodBuilderCore.Start) clearly visible.
  • With runtime-async: 5 frames, the real call chain (InnerAsync, MiddleAsync, OuterAsync, Main$, Main).

Exception stack traces (inside a catch) already look the same with or without Runtime Async, because the existing ExceptionDispatchInfo cleanup in compiler-generated code handles that case. The gain is for profilers, diagnostic logging and the debugger's call stack window.

NativeAOT, ReadyToRun and debugging

  • NativeAOT and ReadyToRun: Runtime Async also works with ahead-of-time compilation. The runtime reuses continuation objects more aggressively and avoids saving unchanged locals, which reduces allocation pressure.
  • Debugging: breakpoints now bind correctly inside runtime-async methods, and the debugger can step through await boundaries without jumping into compiler-generated infrastructure.
  • Covariant Task to Task<T> overrides: when a derived class returns Task<T> for a base method that returns Task, the runtime generates a void-returning thunk that bridges the calling-convention difference, so virtual dispatch works for both flavors. The same fix applies to NativeAOT.
  • Inlining in crossgen2: the restrictions that prevented inlining of runtime-async methods during R2R compilation were removed. All async tests pass with both crossgen2 and composite R2R, and inlining of await-less async calls (the synchronous fast path) is confirmed end to end.

Performance improvements

  • JIT async support: the JIT compiles a dedicated runtime-async version of a synchronous, task-returning method rather than going through a thunk. It turns the method's tail calls into runtime-async calls and awaits the task that would otherwise be returned, removing a layer of indirection.
  • Tail-merged suspension points: the generated code is smaller.
  • Cached continuations: continuations used for runtime-async callable task thunks are cached and reused.
  • Pooled methods opt out: methods that are already pooled opt out of runtime-async, avoiding redundant work.
  • Tiered async compilation: async versions flow through tiered compilation, so hot async methods get tier 1 optimizations after warm-up.
  • Task and ValueTask factory intrinsics: the JIT recognizes Task.FromResult, Task.CompletedTask and ValueTask.FromResult and folds them into faster async paths.
  • Tail-await optimizations: implicit tailcalls from async methods are enabled again when the method directly returns another async result, and await Task.Yield() avoids extra allocations in runtime-async paths.

Continuations without ExecutionContext

ExecutionContext carries ambient state, such as AsyncLocal<T> values, across await points. Every Task continuation used to capture a snapshot of the context and restore it before running, even when no AsyncLocal<T> state was in use and the restore was a no-op.

The runtime now detects when a continuation has nothing to restore and skips the capture/restore cycle entirely. Task, Task<T>, ValueTask and ValueTask<T> all benefit, as does the runtime-async implementation path. Applications that use ConfigureAwait(false) and AsyncLocal<T> sparingly see reduced overhead in high-throughput async code paths.

Diagnostics

The async profiler now instruments both runtime-async methods and compiler-generated async state-machine methods, so tools receive one consistent event model regardless of the async implementation style.

Sources


.NET 11: JIT, NativeAOT, WebAssembly and hardware requirements

Beyond Runtime Async, the .NET 11 runtime brings a long list of changes: more modern hardware requirements, a JIT that removes more checks, new Arm and x86 intrinsics, CoreCLR on WebAssembly, in-process crash reports, faster NativeAOT interface dispatch and several reliability fixes. This article collects all of them, following the official documentation.

Minimum hardware requirements

.NET 11 requires more modern instruction sets on x86/x64 and Arm64, and updates the ReadyToRun (R2R) targets as well.

Arm64

OSJIT/AOT minimumR2R target
AppleApple M1 (no change)Apple M1 (no change)
Linuxarmv8.0-a (no change)from armv8.0-a to armv8.0-a + LSE
Windowsfrom armv8.0-a to armv8.0-a + LSEfrom armv8.0-a to armv8.2-a + RCPC

Linux still supports devices such as Raspberry Pi that may only offer AdvSimd; the new R2R target with LSE can add jitting overhead at launch. On Windows, the LSE baseline is required by Windows 11 and by all Arm64 CPUs officially supported by Windows 10, and it matches the Arm SBSA requirements.

x86/x64

OSJIT/AOT minimumR2R target
Applefrom x86-64-v1 to x86-64-v2x86-64-v2 (no change)
Linuxfrom x86-64-v1 to x86-64-v2from x86-64-v2 to x86-64-v3
Windowsfrom x86-64-v1 to x86-64-v2from x86-64-v2 to x86-64-v3

x86-64-v2 guarantees CX16, POPCNT, SSE3, SSSE3, SSE4.1 and SSE4.2 on top of CMOV, CX8, SSE and SSE2. x86-64-v3 adds AVX, AVX2, BMI1, BMI2, F16C, FMA, LZCNT and MOVBE. On hardware that does not meet the baseline, .NET fails to run and may print "The current CPU is missing one or more of the baseline instruction sets". The stated reason is to reduce maintenance complexity and align with the requirements of the underlying operating systems.

JIT improvements

  • Bounds checks: eliminated for the i + cns < len pattern, with more redundant checks removed for index-from-end access (values[^1]); after a !span.IsEmpty guard, the check on span[0] disappears.
  • Redundant checked contexts: the JIT proves and removes them when a value is already in range.
  • Switch expressions: multi-target switches over a small set of constants (such as x is 0 or 1 or 2 or 3 or 4) fold into branchless checks.
  • Faster uint-to-float/double casts on pre-AVX-512 x86 hardware.
  • Constant-folded SequenceEqual: string.Equals and ReadOnlySpan<T>.SequenceEqual with constant operands become true or false; this covers string literals, const string fields and UTF-8 literals such as "PNG"u8.
  • Devirtualization: generic virtual methods (including shared ones that need no runtime lookup), default interface methods on generic interfaces, and the result of Activator.CreateInstance<T>() treated as an exact type. This unlocks inlining and constant folding.
  • Redundant branches and tests: removed when an outer predicate is implied by an inner branch, or when a value assigned in a conditional is tested right away.
  • Math.BigMul(long, long, out long) on x64: a single MUL r/m64 instruction, with no helper call.
  • Prolog: the restriction that it fit in a single instruction group was removed.
  • SELECT(cond, cns, cns): when both branches produce the same constant, the JIT uses that constant directly.
  • Saturating conversions: unchecked float and double conversions to small integer types saturate to the type bounds instead of wrapping.
  • Vector<T> on Arm64 with SVE: passed by reference, matching the Arm calling convention for scalable types.

Hardware intrinsics and code generation

  • Arm SVE2: new ShiftRightLogicalNarrowingSaturate(Even|Odd) intrinsics; CreateWhile gains signed, double and single variants; the runtime now reports SVE_AES, SVE_SHA3, SVE_SM4, SHA3 and SM4 as separate instruction sets, queryable through Sve2*.IsSupported.
  • AVX-VNNI-512: System.Runtime.Intrinsics.X86.AvxVnni.V512 exposes the 512-bit forms of the multiply-add intrinsics on CPUs with AVX512-VNNI.
  • Hardware FP16 for Half: on x64, arithmetic uses AVX10.1 and conversions to float can use F16C; on Arm64, arithmetic uses the optional FP16 instruction set and conversions use baseline instructions. No app changes are needed and the ABI representation of Half is preserved.
  • x86/x64 SIMD cost model: costs updated for modern SSE/AVX instead of x87-era assumptions, improving hoisting and CSE decisions.
  • Faster DotProduct on AVX: a mul + permute + add sequence instead of vdpps/vdppd.
  • Arm64: Vector*.Count, IndexOf and LastIndexOf (IndexOfAnyAsciiSearcher) no longer go through ExtractMostSignificantBits, giving a 5-50% improvement in workloads that use them in their core loop; ToScalar on Vector*<long> and Vector*<ulong> uses fmov instead of umov.
  • AVX10: fixed a bug where the CPUID-bit cache was overwritten by a later query, which could misreport AVX10 on capable hardware.

SIMD lane APIs

System.Runtime.Intrinsics adds APIs to build a vector from individually specified lanes and to extract or reorder lanes between vectors, available on Vector64<T>, Vector128<T>, Vector256<T>, Vector512<T> and Vector<T>:

  • patterned construction: CreateGeometricSequence, CreateAlternatingSequence, CreateHarmonicSequence;
  • interleave and de-interleave: Zip, ZipLower/ZipUpper, Unzip, UnzipEven/UnzipOdd;
  • rearrangement: the Concat family (ConcatLowerLower, ConcatLowerUpper, ConcatUpperLower, ConcatUpperUpper) and Reverse.
// {1, 2, 4, 8}: each lane is the previous lane times two
Vector128<int> powers = Vector128.CreateGeometricSequence(1, 2);
// Interleave two vectors lane by lane
(Vector128<int> lower, Vector128<int> upper) =
    Vector128.Zip(Vector128.Create(1), Vector128.Create(2));

ReadyToRun and VM

  • R2R: Comparer<T>.Default and EqualityComparer<T>.Default are specialized in R2R images, mirroring NativeAOT. Previously they relied on reflection R2R could not see ahead of time, so callers fell back to the JIT; collection operations that use the default comparers improve by up to 20x.
  • Cached interface dispatch on platforms without JIT support, such as iOS: up to 200x improvement in interface-heavy code.
  • Guid.NewGuid() on Linux: uses the getrandom() syscall with batch caching instead of /dev/urandom, for roughly 12% more throughput.
  • More than 1024 CPUs: the runtime can initialize on machines with more than 1024 logical processors by allocating the CPU set dynamically. The GC keeps its 1024-heap limit.

CoreCLR on WebAssembly

  • The runtime can load WebCIL payloads directly; WebCIL V1 (header grows from 28 to 32 bytes with a TableBase field) is the default for CoreCLR WASM builds, and both Mono and CoreCLR readers accept V0 and V1.
  • Better symbols and stack traces for debugging.
  • float[], Span<float> and ArraySegment<float> are marshaled more directly across JavaScript boundaries.
  • Native re-link works: a full Emscripten-based pipeline replaces the stub targets, so you can re-link dotnet.native.wasm and include custom native code with NativeFileReference.
  • Browser CoreCLR Release builds ship minified JavaScript.
  • NativeAOT publish for WASM no longer drops satellite assemblies from NuGet packages, which fixes localization (for example with System.CommandLine).
  • CoreCLR on WebAssembly now runs the libraries test suite end to end.

In-process crash reports

A new mechanism captures diagnostic information from inside the crashing process before it terminates, logging the managed stack trace, the module list and key runtime state to a well-known path. It originated on mobile platforms and is now also available on Linux and macOS. When DOTNET_DbgEnableMiniDump is not enabled, set DOTNET_EnableCrashReport=1 or DOTNET_EnableCrashReportOnly=1; existing createdump behavior stays in place when minidumps are enabled.

NativeAOT: interface dispatch

  • Interface method calls go through a shared helper that can be patched after the call site warms up, giving smaller binaries and better throughput.
  • Generic virtual methods use the same shared dispatch-cell infrastructure, improving monomorphic and polymorphic calls.
  • Assembly.GetCallingAssembly() now works on NativeAOT when stack trace data is available.

File locking on iOS and tvOS

On iOS and tvOS, simulators included, CoreCLR now disables advisory file locking by default: a FileStream holding an advisory lock could cause the operating system to terminate an app that moved to the background. As a result, FileShare restrictions are no longer enforced by those locks, even between handles in the same process. Mac Catalyst and other platforms keep their defaults. To restore locking, accepting the risk of suspension-related termination, set DOTNET_SYSTEM_IO_DISABLEFILELOCKING=0 or the System.IO.DisableFileLocking property to false in runtimeconfig.json.

Reliability and diagnostics

  • Linux: the SDK no longer crashes on RHEL 8 on Arm64, and the runtime correctly traverses cgroup v2 memory limits at the root of the hierarchy.
  • Array marshalling to native code now produces correct values and avoids unexpected exceptions.
  • Sharing Unix named mutexes with older .NET processes no longer causes spurious abandoned-mutex errors.
  • macOS: terminating a process tree no longer hangs.
  • Generic virtual method dispatch no longer hangs after repeated AssemblyLoadContext unloads.
  • TryDequeue and TryPeek no longer spuriously report an empty queue while a segment freezes during growth.
  • Windows: garbage collection works correctly on machines with multiple CPU groups.
  • Diagnostics: improved interpreter perf-map logging, and a fix for parsing CORECLR_NOTIFICATION_PROFILERS lists that do not end with a semicolon.

Sources


.NET 11 libraries: processes, compression, numbers and in-memory streams

.NET 11 is generally available, and the base libraries grow in many directions. This first article collects what is new for process execution, text, compression and archives, numerics, in-memory streams, low-level I/O and collections. The sections come from the official libraries page; the rest (JSON, networking, cryptography, diagnostics) is in the second article of the series.

Process: running and capturing output

The Process class gets a large set of APIs for scenarios that used to need OutputDataReceived/ErrorDataReceived events or P/Invoke.

ProcessTextOutput result = await Process.RunAndCaptureTextAsync(
    "git", ["status", "--porcelain"]);
Console.WriteLine(result.StandardOutput);
Console.WriteLine($"Exit code: {result.ExitStatus.ExitCode}");
  • Run and capture: Process.Run/RunAsync, RunAndCaptureText/RunAndCaptureTextAsync, ReadAllText, ReadAllBytes (plus async variants), ReadAllLines and ReadAllLinesAsync, which tell stdout from stderr through ProcessOutputLine.
  • Fire and forget: Process.StartAndForget, ProcessStartInfo.StartDetached (the child can outlive a terminal exit) and KillOnParentExit (Windows only).
  • SafeProcessHandle: Start, the ProcessId property, Kill(), Signal(PosixSignal), WaitForExit() and WaitForExitAsync.
  • Handle control: InheritedHandles, and StandardInputHandle/StandardOutputHandle/StandardErrorHandle taking already-open SafeFileHandle values.
  • Suspended start and lookup: StartSuspended (Windows and macOS) paired with SafeProcessHandle.Resume(); Process.TryGetProcessById, Open and TryOpen.
  • Signals and exit status: Process.Signal(PosixSignal), WaitForExitStatus, TryWaitForExitStatus and WaitForExitStatusAsync return a ProcessExitStatus that separates a normal exit from a signal-based termination.

The console also honors the FORCE_COLOR standard next to NO_COLOR: when set, Console.IsOutputRedirected no longer suppresses ANSI escape codes (handy with tee, CI log viewers or less -R). On Windows, Process uses overlapped I/O for redirected stdout/stderr, which reduces thread-pool blocking.

Streams over in-memory data

Four new Stream types wrap in-memory data without copying it into a MemoryStream:

  • ReadOnlyMemoryStream, a read-only stream over ReadOnlyMemory<byte>;
  • WritableMemoryStream, a fixed-size stream over Memory<byte>;
  • ReadOnlySequenceStream, over ReadOnlySequence<byte> (for example from System.IO.Pipelines) without flattening segments;
  • StringStream, which reads a string or ReadOnlyMemory<char> with a chosen encoding.

Text, Base64 and UTF validation

  • Runes: String accepts Rune in Contains, StartsWith, EndsWith, IndexOf, LastIndexOf, Replace, Split, Trim, TrimStart, TrimEnd, with many StringComparison overloads; TextInfo adds ToLower(Rune) and ToUpper(Rune); Char.Equals(Char, StringComparison) is new.
  • StringBuilder.MoveChunks: moves content into a new StringBuilder without copying characters; the source ends at length 0.
  • Base64: EncodeToChars, EncodeToString, EncodeToUtf8, DecodeFromChars, DecodeFromUtf8, both convenient and span-based.
  • UTF: Utf16.IsValid, Utf8.IndexOfInvalidSubsequence and Utf16.IndexOfInvalidSubsequence (position of the first error, or -1) allow precise error reporting.
  • Regex: RegexOptions.AnyNewLine makes ^, $ and . treat all Unicode newlines as line terminators; the non-backtracking engine avoids super-linear time on certain nested loops, and the compiler and source generator fix conditionals inside loops and duplicate class names (SYSLIB1045).

Compression and archives

  • Zstandard: ZstandardStream and ZstandardEncoder move into the System.IO.Compression namespace; ZstandardDictionary.Train and Create handle dictionaries.
  • ZIP: ZipArchiveEntry.Open(FileAccess) and OpenAsync; a CompressionMethod property (Stored, Deflate, Deflate64); password-protected entries with ZipEncryptionMethod.
  • CRC32 validation: corrupted or truncated archives that used to pass now throw InvalidDataException.
  • DeflateStream and GZipStream: always write headers and footers, even with no data, so the output is a valid stream per the specifications (a behavior change).
  • Span-based APIs: DeflateEncoder, ZLibEncoder, GZipEncoder and their decoders compress and decompress buffers without a Stream, with a Reset() method for reuse.
  • Tar: CreateFromDirectory/CreateFromDirectoryAsync overloads take a TarEntryFormat (Pax, Ustar, GNU, V7); TarReader also reads the GNU sparse 1.0 format.

Numbers and math

  • Decimal32, Decimal64, Decimal128: in System.Numerics, with IEEE 754-2019 semantics, generic math, infinities and NaN. Transcendental functions are more accurate (for example Decimal128.Acos(1 - 1e-30) used to be far off and is now well under one ULP); because results change, last digits compared with stored values may differ.
  • Correctly rounded conversions: from Decimal and BigInteger to binary floating-point types, with a single rounding; there is no switch to restore the old algorithms. Converting the double literal 1.23 no longer yields 1.23, so use 1.23m when the value is meant to be decimal.
  • TryParsePartial: INumberBase<TSelf>.TryParsePartial reports how much input was consumed, useful for CSV without substrings.
  • Complex<T>: complex arithmetic over float, Half, BFloat16 and the new decimal types.
  • BFloat16 in BitConverter: GetBytes, ToBFloat16 and bit conversions.
  • IEEE-754 hex form: double, float and Half format and parse as hexadecimal (ToString("X"), NumberStyles.HexFloat) with an exact round trip.
  • Generic Random: Random.NextInteger<T> and Random.NextBinaryFloat<T>.
  • Vectors: Vector64/128/256/512<T> and Vector<T> add patterned construction (CreateGeometricSequence, CreateAlternatingSequence, CreateHarmonicSequence), Zip/Unzip, the Concat family and Reverse.
  • Matrix4x4.GetDeterminant(): SSE-vectorized, about 15% faster.

Low-level I/O

  • SafeFileHandle.Type tells whether a handle is a file, pipe, socket or directory; SafeFileHandle.CreateAnonymousPipe creates connected pipe handles with independent async behavior per end.
  • RandomAccess.Read and Write now work with non-seekable handles such as pipes.
  • On iOS and tvOS, FileStream no longer takes advisory locks by default (FileShare restrictions are not enforced); restore it with System.IO.DisableFileLocking set to false or DOTNET_SYSTEM_IO_DISABLEFILELOCKING=0.

Collections and Tensors

  • BitArray: constructors from ReadOnlySpan<bool>, <byte>, <int>, and a PopCount() method.
  • EqualityComparer<T>.Create: builds a comparer from a key selector.
  • ConcurrentQueue<T>: TryDequeue and TryPeek no longer report an empty queue by mistake while it grows.
  • System.Numerics.Tensors: updating the package changes shape alignment and rejects unsupported overlapping storage layouts, even on frameworks older than .NET 11: review code that relies on particular shapes or overlapping copies.

Developer platform

  • Discriminated-union scaffolding: UnionAttribute and IUnion, not yet meant for direct use.
  • MetadataLoadContext.GetLoadContext, Type.GetNullableUnderlyingType(), ConstructorInfo.GetGenericArguments(), AssemblyLoadContext.SetAssemblyLocationOverride, Uri.UriSchemeData, and StringSyntax constants for C#, F# and Visual Basic.
  • System.IO.Pipelines reduces reader and writer contention under high fan-in.

The rest is in the article on JSON, networking and security; for command-line tooling see the SDK article.

Sources


.NET 11 libraries: JSON, networking, cryptography, validation and diagnostics

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.SerializeAsyncEnumerable overloads target a Stream or PipeWriter; with topLevelValues: true they stream canonical JSON Lines (one compact value per line, LF-terminated, ignoring WriteIndented).
  • Closed hierarchies: with InferClosedTypePolymorphism (on options, the generator or JsonPolymorphicAttribute) the serializer infers derived types and assigns deterministic discriminators; explicit JsonDerivedTypeAttribute registrations take precedence. Open generic derived registrations such as Derived<> are supported too.
  • Source generation: [JsonInclude] members with private, internal or protected accessors; inaccessible constructors marked with JsonConstructorAttribute; in, ref, out and ref readonly parameters; omitted init-only properties keep their initializer value.
  • GetTypeInfo<T>() and TryGetTypeInfo<T>(): return JsonTypeInfo<T> without a cast.
  • Naming and ignoring: JsonNamingPolicy.PascalCase, JsonNamingPolicyAttribute on a type or member, JsonIgnoreAttribute with a type-level condition (Always is invalid at type level).
  • Converters and collections: built-in converters for BFloat16, Decimal32, Decimal64, Decimal128; open generic converters; JsonExtensionData on IReadOnlyDictionary; IReadOnlySet<T> as an array.
  • Utf8JsonWriter: Reset with JsonWriterOptions lets 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: ShouldEvictConnection retires connections by age, endpoint and DNS changes; InitialHttp2MaxConcurrentStreams limits the initial burst before the SETTINGS frame (minimum value 1).
  • DNS: Dns.ResolveSrv, ResolveMx, ResolveTxt, ResolveCName, ResolvePtr, ResolveNs (and Async variants) with DnsResult<T>; the DnsResolver class with DnsResolverOptions accepts custom DNS servers and now works on Linux too.
  • HTTP/2: HttpClient automatically downgrades to HTTP/1.1 when Windows authentication (NTLM/Negotiate) is required.
  • QUIC: QuicStream.Priority (0 to 255, default 127) and DefaultPriority.
  • Also: MediaTypeNames.Video constants; the HTTP open_connections and active_requests metrics become observable instruments (call MeterListener.RecordObservableInstruments()).

Cryptography

  • X25519: the X25519DiffieHellman class with GenerateKey() and DeriveRawSecretAgreement, 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: AesGcm and ChaCha20Poly1305 avoid passing empty associated data to CryptoKit.
  • ML-KEM and HPKE (experimental): CompositeMLKem (SYSLIB5006) combines post-quantum and classical KEMs; Hpke (SYSLIB5009) uses HpkeSuite with Seal and Open. Suite availability depends on the platform.
  • CMS: EnvelopedCms encrypts with pure ML-KEM recipients, on non-Windows platforms only.

Configuration, options and validation

  • Binding: ConfigurationIgnoreAttribute opts properties out of binding; empty arrays bind to constructor parameters; PhysicalFilesWatcher is more reliable with missing directories and file systems without watching.
  • OptionsBuilder: Validate<TValidator>() with an IValidateOptions<TOptions> registered in DI.
  • ChangeToken.OnChange: Func<Task> overloads, no async void.
  • HybridCache: GetOrCreateAsync overloads with a mutable context for expiration and local cache size.
  • Async DataAnnotations: AsyncValidationAttribute, IAsyncValidatableObject, Validator.ValidateObjectAsync and friends; async options validation with IAsyncValidateOptions and IAsyncStartupValidator (IStartupValidator is obsolete); ValidationAttribute.FormatMessage for localization.

Diagnostics and logging

  • MemoryCache and OpenTelemetry: with TrackStatistics = true, the Microsoft.Extensions.Caching.Memory.MemoryCache meter publishes dotnet.cache.requests (tag dotnet.cache.request.result), dotnet.cache.evictions, dotnet.cache.entries and dotnet.cache.estimated_size; an IMeterFactory gives per-instance metrics.
  • Rule-based tracing: AddTracing with EnableTracing/DisableTracing for sources and operations, drivable from configuration; ActivitySourceFactory and an unsealed ActivitySource.
  • Generic logging: generic LoggerMessage methods avoid boxing (the allows ref struct anti-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


.NET 11 SDK and CLI tooling: everything new and how to upgrade

The .NET 11 SDK brings smaller installers, refined analyzers, a much more convenient CLI and important changes for testing, containers, MSBuild and NuGet. This article summarizes the official page and ends with instructions for upgrading your SDK.

SDK footprint

On Linux and macOS, duplicate assemblies (.dll and .exe files with the same hash) are replaced with symbolic links to a single copy, for tarballs, .pkg, .deb and .rpm. According to the source, an early build had 35% of the SDK directory duplicated; on linux-x64 the tarball goes from 230 to 189 MB (-17.8%), the deb from 164 to 122 MB (-25.6%), the rpm from 165 to 122 MB (-26.0%), and containers save 8-17%. Crossgen is also skipped for assemblies that exist only under DotnetTools/, saving another 23.6 MB. Windows deduplication is not included.

Analyzers and warnings

  • CA1873 (potentially expensive logging) has fewer false positives: property accesses, GetType(), GetHashCode() and GetTimestamp() are no longer flagged, and by default only Information level and below is checked. The message now states the reason (method invocation, object or array creation, boxing, string interpolation, collection expression, anonymous object, await, with expression).
  • Fixes: CA1515 and CA1034 no longer misfire with C# extension members; CA1859 handles default interface implementations; AnalysisLevel=latest wrongly used .NET 9 rules and now uses .NET 11 rules.
  • NETSDK1235: a warning when a project with PackAsTool=true sets a custom NuspecFile; packing still proceeds.

Command-line productivity

  • Solution filters: dotnet new slnf --parent-solution MySolution.slnx --name Tests, then dotnet sln Tests.slnf add|list|remove.
  • File-based apps across files: the #:include directive (also for DLLs, mapped to Reference items, with no feature flag); #:sdk, #:property and #:package may appear duplicated across included files when the values match. #:property accepts quoted values; #:package, #:project and #:ref accept trailing Name=Value metadata tokens (for example Aliases=CommandLine). A : is no longer allowed in property names.
  • Native AOT for file-based apps: dotnet run --file app.cs, dotnet run app.cs and dotnet app.cs can reuse existing build outputs; dotnet format app.cs works; with the artifacts layout, outputs go to the repository's artifacts folder.
  • dotnet run -e: dotnet run -e ASPNETCORE_ENVIRONMENT=Development -e LOG_LEVEL=Debug passes environment variables, visible to MSBuild as RuntimeEnvironmentVariable items; MSBuild properties in launch-profile commandLineArgs are expanded; the "Using launch settings from..." notice goes to stderr.
  • dotnet watch: Aspire app host integration, automatic relaunch after a crash, better Ctrl+C for Windows Forms and WPF, device selection for MAUI and mobile (dotnet watch --device <device-id>), browser refresh for static SSR pages in Blazor Web apps, and several long-standing bugs fixed. iOS Simulator projects need <MtouchLink>None</MtouchLink>.
  • dotnet reference: add and remove fall back to the current directory without --project and support file-based apps (dotnet reference add --file app.cs).
  • More: static fish shell completions; dotnet format limits .editorconfig discovery to included files (one benchmark went from 1.09 to 0.55 seconds) and accepts --framework; dotnet test in MTP mode supports --artifacts-path; dotnet tool exec and dnx no longer ask for an extra approval; dotnet new install --prerelease; the Configuration environment variable supplies the default for -c; concurrent tool installs no longer race.

CLI architecture and telemetry

  • NativeAOT entry point: enabled by default (opt out with DOTNET_CLI_ENABLEAOT=false). Commands such as dotnet --version, --info, --help, --cli-schema and dotnet sln list/migrate/remove run natively; everything else falls back to the managed CLI. Tools and external commands such as dotnet ef or dotnet dev-certs launch out of process, skipping the 600-700 ms managed startup.
  • MSBuild server: on by default; opt out with DOTNET_CLI_USE_MSBUILD_SERVER=false or MSBUILDUSESERVER=0. When the former is unset, the CLI no longer forces MSBUILDUSESERVER=0.
  • OpenTelemetry telemetry: replaces Application Insights with Azure Monitor and OTLP exporters; behavior and the DOTNET_CLI_TELEMETRY_OPTOUT opt-out are unchanged. The OTLP exporter also turns on when standard OTEL_EXPORTER_OTLP_* variables are present.
  • Optimized Native AOT publish: opt-in by setting both PublishAot and UseOptimizedPublish to true; the source says it becomes the default from .NET 12 Preview 1.
  • Partial Ready-to-Run: an MSBuild property meant for mobile workloads (macios, MAUI), not for apps.
  • Static Web Assets: Asset Groups, AdditionalEndpointDefinitions and TypeScript output integration.

dotnet test

  • MTP options: --no-dependencies, the DOTNET_TEST_RUNNER variable (VSTest or Microsoft.Testing.Platform), --use-current-runtime/--ucr, ! exclusions in --test-modules, per-assembly counts, --tl forwarding, live in-flight tests, two-stage Ctrl+C, live output with protocol 1.1.0.
  • Mobile testing: Android, iOS, macOS and Mac Catalyst with --device and the androidtest, iostest, macostest, maccatalysttest templates (MSTest by default); dotnet test -bl records everything in one binary log.
  • Run-level policies: --timeout 90s (exit code 3), --maximum-failed-tests 5 (exit code 13), --results-directory-layout per-module, default artifacts layout and --nologo.
  • Experimental: affected-test selection with --collect-test-map and --affected-tests, through a separate extension and DOTNET_CLI_ENABLE_AFFECTED_TESTS=1.
  • More: traversal projects (dotnet test dirs.proj), better reporters, dotnet new xunit --xunit-version v3 and dotnet new nunit --test-runner Microsoft.Testing.Platform.

MSBuild, NuGet and containers

  • Faster wildcards: with SDK 11.0.100 or Visual Studio 18.12, full evaluations are 10-13% faster with 16-34% fewer allocations (on four measured workloads).
  • NuGet: --min-publish-age-hours for dotnet nuget add source and update source; dotnet package add/update apply it; for floating references, restore fails with NU1020.
  • Containers: multi-arch builds with Podman, platform-native local runtimes preferred (wslc on Windows, container on macOS), reproducible publishing with SOURCE_DATE_EPOCH and an existing-manifest check (ContainerPushNoCache=true bypasses it).

Upgrading your SDK

.NET 11 is generally available. To install or upgrade the SDK, use these official pages, all verified with an HTTP request:

After installing, check the version with dotnet --version and, if you use a global.json, update it accordingly.

Sources


What's new in C# 15: unions, closed and more

C# 15 ships with the .NET 11 SDK (or a compatible version of Visual Studio 2026) and brings seven features: collection expression arguments, union types, closed hierarchies, extension indexers, labeled break and continue, non-virtual static interface members on older runtimes and, as a preview, new memory safety rules. Here is what changes, with the examples from the official documentation.

Getting C# 15

  • C# 15 is the default language version for projects that target net11.0 in the .NET 11 SDK.
  • Only the memory safety preview feature requires <LangVersion>preview</LangVersion>.

Get the SDK from the .NET 11 download page.

Collection expression arguments

A with(...) element as the first element of a collection expression passes arguments to the underlying collection's constructor or factory method: capacity, comparers or other parameters, right inside the collection expression syntax.

string[] values = ["one", "two", "three"];
List<string> names = [with(capacity: values.Length * 2), .. values];
HashSet<string> set = [with(StringComparer.OrdinalIgnoreCase), "Hello", "HELLO", "hello"];
// set contains only one element

Union types

The union keyword declares a value that can be one of several case types. A union gets implicit conversions from each case type, and the compiler ensures that switch expressions are exhaustive across all the cases.

public record class Cat(string Name);
public record class Dog(string Name);
public record class Bird(string Name);
public union Pet(Cat, Dog, Bird);

Pet pet = new Dog("Rex");
string name = pet switch
{
    Dog d => d.Name,
    Cat c => c.Name,
    Bird b => b.Name,
};

Closed hierarchies

The closed modifier on a class declares a closed hierarchy: the class can only be derived from within its declaring assembly, so the direct descendants are fixed at compile time. A switch expression that handles each one is exhaustive and needs no default arm.

public closed record class GateState;
public record class Closed : GateState;
public record class Open(float Percent) : GateState;

string Describe(GateState state) => state switch
{
    Closed => "closed",
    Open(var percent) => $"{percent}% open",
};
  • closed is a contextual keyword.
  • A closed class is implicitly abstract and can't be combined with sealed, static or an explicit abstract.
  • Derivation isn't transitive: a non-closed descendant can still be derived from in other assemblies. To extend exhaustiveness checking down the hierarchy, mark intermediate descendants closed too.

Extension indexers

An extension block can now declare indexers, so you can index into a receiver as though the indexer were declared on the receiver type. Indexers are always instance members, so the block must provide a named receiver parameter.

public static class SequenceIndexer
{
    extension(IEnumerable<int> sequence)
    {
        public int this[int index] => sequence.ElementAt(index);
    }
}

IEnumerable<int> numbers = Enumerable.Range(1, 10);
int third = numbers[2];

Labeled break and continue

break and continue can name a label on an enclosing construct: a labeled break exits an enclosing loop or switch, a labeled continue starts the next iteration of an enclosing loop. They replace the Boolean flags or goto jumps you would otherwise use to steer control flow through nested loops. Put the label directly on the loop or switch it identifies; without a label, the statements behave as before. The IDE0410 style rule flags the flag and goto patterns that a labeled jump can replace.

outer: for (int row = 0; row < grid.Height; row++)
{
    for (int column = 0; column < grid.Width; column++)
    {
        if (grid[row, column].IsBlocked)
        {
            continue outer;
        }
        if (grid[row, column].IsGoal)
        {
            break outer;
        }
    }
}

Non-virtual static interface members on older runtimes

Starting in C# 15 you can declare and use non-virtual static interface members even when the target runtime doesn't support default interface implementations. Call the helper directly on the interface, for example IMeasurement.ToMeters(250).

public interface IMeasurement
{
    public static double ToMeters(double centimeters) => centimeters / 100;
}
// IMeasurement.ToMeters(250)

Instance default implementations, static abstract and static virtual members, and protected interface members still require runtime support.

Memory safety (preview)

The .NET 11 SDK includes a memory safety preview feature that starts a multirelease effort to redefine memory safety: the unsafe context is tied to the operations that actually access unmanaged memory, rather than to the existence of pointer types. With the updated rules, unsafe on a member marks it as requires-unsafe and the audit obligation flows to the caller. The compiler records the use of the rules with MemorySafetyRulesAttribute, and a new safe contextual keyword marks extern members and fields in explicit or extended layout types.

With the preview language version, these no longer require an unsafe context: declaring a pointer type and taking an address with &, the fixed statement, converting stackalloc to a pointer, and sizeof on any unmanaged type.

int number = 42;
int* pointer = &number;

int[] numbers = [10, 20, 30];
fixed (int* first = numbers)
{
    // Dereferencing the pointer still requires an unsafe context.
}

Pointer indirection (*p), member access (p->member), element access (p[i]) and function pointer invocation still require an unsafe context. C# 15 also adds the unsafe(expression) expression, handy where an unsafe block can't appear, such as a field initializer, a constructor initializer or a catch filter:

class Header
{
    static readonly int Signature = unsafe(ReadSignature());

    static unsafe int ReadSignature()
    {
        unsafe
        {
            int rawValue = 0x1234;
            int* pointer = &rawValue;
            return *pointer;
        }
    }
}

Unsafe expressions require the preview language version and the AllowUnsafeBlocks option. To also enable the updated rules, turn on the updated-memory-safety-rules compiler feature.

Sources


What's new in EF Core 11: complex types, vectors, Cosmos

EF Core 11 brings news in almost every area: more mature complex types, better LINQ and SQL, many SQL Server features (vector search, full-text, JSON), improvements for SQLite and Azure Cosmos DB, and new migration tooling. Below is one section per feature, with code from the official documentation.

How to upgrade

  • EF Core 11 requires the .NET 11 SDK to build and the .NET 11 runtime to run.
  • It does not run on earlier .NET versions or on .NET Framework.

Download .NET 11 from the official page.

Complex types

Complex types and JSON columns with TPT/TPC inheritance

Until now, complex types and JSON columns could not be used on entities with TPT (table-per-type) or TPC (table-per-concrete-type) inheritance. EF 11 supports them: for an Animal entity with AnimalDetails as a complex type, EF creates the Details_BirthDate and Details_Veterinarian columns on the Animal table, or maps the property to a JSON column.

modelBuilder.Entity<Animal>().UseTptMappingStrategy();

modelBuilder.Entity<Animal>()
    .UseTptMappingStrategy()
    .ComplexProperty(a => a.Details, b => b.ToJson());

Configuring via lambda chaining

You no longer need to go through ComplexProperty to configure a complex type property: just chain member access in the lambda passed to Property.

modelBuilder.Entity<MyEntity>()
    .Property(e => e.Details.Description)
    .HasMaxLength(500);

Keys and indexes on complex type properties

Keys and indexes can use scalar properties nested inside non-collection complex types, also by name ("Address.PostalCode"). For relational providers, indexes can also target paths inside complex types mapped to JSON columns; in complex collections, [] means all elements and a numeric indexer a specific one.

modelBuilder.Entity<Customer>()
    .HasIndex(c => c.Address.PostalCode);

modelBuilder.Entity<Order>()
    .ComplexCollection(o => o.Items, b => b.ToJson());
modelBuilder.Entity<Order>()
    .HasIndex("Items[].Sku");

Stabilization

Significant effort went into stabilizing complex types so they can be an alternative to owned entities. Fixed bugs include queries on complex types whose container is mapped to a table and a view, ComplexProperty with TPT, comparison of nested complex types, assignment in ExecuteUpdate, and ReloadAsync with a null nullable complex property. Complex types are also supported in Azure Cosmos DB (see below).

LINQ and SQL translation

Better SQL for to-one joins

With split queries (AsSplitQuery()) EF no longer adds unnecessary joins to reference navigations, and no longer adds redundant keys from reference navigations to ORDER BY. The documentation reports a 29% improvement in a common split query scenario and 22% in a single query scenario; actual performance depends on your schema and data.

GroupBy enhancements

Translation and materialization of GroupBy queries improve: you can compose navigation access and joins over a per-group top result, aggregates over reference navigations use joins before grouping instead of correlated subqueries, and left-joined non-entity projections (anonymous types, DTOs) are materialized correctly.

FullJoin

.NET 11 adds the LINQ FullJoin operator, which EF Core 11 translates to FULL JOIN on relational databases.

var results = await context.Customers
    .FullJoin(
        context.Orders,
        c => c.Id,
        o => o.CustomerId,
        (c, o) => new { Customer = c, Order = o })
    .ToListAsync();

Stripping of no-op CASTs

EF no longer generates CAST expressions that convert a column to the type it already has (common with value-converted properties): they are stripped during SQL post-processing, so the database can use indexes on the column.

MaxBy and MinBy

MaxBy/MinBy (and the async versions) are now translated, returning the element with the maximum or minimum key value. The example finds the blog with the most posts and produces SELECT TOP(1) ... ORDER BY (SELECT COUNT(*) ...) DESC.

var blogWithMostPosts = await context.Blogs.MaxByAsync(b => b.Posts.Count());

SQL Server

JsonPathExists

EF.Functions.JsonPathExists() checks whether a JSON path exists in a JSON document and translates to JSON_PATH_EXISTS (available since SQL Server 2022). It works with scalar string properties, complex types and owned entities mapped to JSON.

var blogs = await context.Blogs
    .Where(b => EF.Functions.JsonPathExists(b.JsonData, "$.OptionalInt"))
    .ToListAsync();

VECTOR_SEARCH() and vector indexes

This is experimental in SQL Server and subject to change, including the EF Core APIs. After EF Core 10's VectorDistance() (exact distance), EF 11 creates vector indexes through migrations and offers VectorSearch() for approximate (ANN) search on SQL Server 2025; without WithApproximate() the search is exact (kNN). The result is VectorSearchResult<TEntity>, with the entity and the distance.

modelBuilder.Entity<Blog>()
    .HasVectorIndex(b => b.Embedding, "cosine");

var blogs = await context.Blogs
    .VectorSearch(b => b.Embedding, embedding, "cosine")
    .OrderBy(r => r.Distance)
    .Take(5)
    .WithApproximate()
    .ToListAsync();

Vector properties not loaded by default

SqlVector<T> columns are no longer included in the SELECT when materializing entities; they remain usable in WHERE and ORDER BY and are loaded with an explicit projection. A minimal benchmark showed an almost 9x improvement against a local database and about 22x against a remote Azure SQL database; real results vary.

Full-text: catalog, index and table-valued functions

Full-text catalogs and indexes are configured in the model and created by migrations (previously you had to add SQL by hand). FreeTextTable and ContainsTable translate FREETEXTTABLE() and CONTAINSTABLE() and return FullTextSearchResult<TEntity>, with the entity and the ranking score (ContainsTable works the same way).

modelBuilder.HasFullTextCatalog("ftCatalog");
modelBuilder.Entity<Blog>()
    .HasFullTextIndex(b => b.FullName)
    .UseKeyIndex("PK_Blogs")
    .UseCatalog("ftCatalog");

var results = await context.Blogs
    .FreeTextTable("John", b => b.FullName)
    .Select(r => new { Blog = r.Value, Rank = r.Rank })
    .OrderByDescending(r => r.Rank)
    .ToListAsync();

Hybrid search

Vector search and full-text table-valued functions can be combined into hybrid search: full-text finds exact linguistic matches, vector search finds semantically similar ones, and the two rankings are merged. FullJoin support makes the pattern more complete; the documentation shows an example that merges the rankings with an RRF score.

JSON_CONTAINS

With SQL Server 2025 (compatibility level 170), Contains queries over primitive collections stored as JSON use JSON_CONTAINS instead of the OPENJSON-based translation, and can use a JSON index. The translation applies only when EF knows that at least one side is non-nullable, because JSON_CONTAINS doesn't search for null values; otherwise it falls back to OPENJSON. For direct use (path, search mode) there is EF.Functions.JsonContains().

optionsBuilder
    .UseSqlServer("<CONNECTION STRING>", o => o.UseCompatibilityLevel(170));

var blogs = await context.Blogs
    .Where(b => EF.Functions.JsonContains(b.JsonData, 8, "$.Rating") == 1)
    .ToListAsync();

JSON indexes

EF Core 11 creates and scaffolds JSON indexes for paths inside complex types mapped to JSON columns, generating CREATE JSON INDEX.

modelBuilder.Entity<Customer>()
    .ComplexProperty(c => c.Contact, b => b.ToJson().HasColumnType("json"));
modelBuilder.Entity<Customer>()
    .HasIndex("Contact.Address.City");

Temporal period properties mapped to CLR properties

The PeriodStart/PeriodEnd properties of temporal tables no longer have to be shadow properties: map them to regular CLR properties with the lambda overloads of HasPeriodStart/HasPeriodEnd and use them directly in queries, without EF.Property. They stay ValueGenerated.OnAddOrUpdate, generated by SQL Server.

modelBuilder
    .Entity<Employee>()
    .ToTable(
        "Employees",
        b => b.IsTemporal(
            b =>
            {
                b.HasPeriodStart(e => e.PeriodStart);
                b.HasPeriodEnd(e => e.PeriodEnd);
            }));

Date/time translations

For DateTimeOffset, the properties DateTime, UtcDateTime, LocalDateTime and Offset.TotalMinutes, the ToOffset method (SWITCHOFFSET) and the constructors from DateTime (TODATETIMEOFFSET) are translated. EF.Functions.DateTrunc() truncates DateTime, DateTimeOffset, DateOnly and TimeOnly to a given precision (DATETRUNC).

Other changes

UseSqlServer now defaults to compatibility level 160 (SQL Server 2022), enabling translations such as LEAST and GREATEST; a breaking change note covers it.

SQLite

With string.Join and string.Concat over a grouping, you can now order with OrderBy/OrderByDescending inside the aggregate: the translation uses group_concat with ORDER BY (requires SQLite 3.44.0 or later; previously such queries fell back to client evaluation). Microsoft.Data.Sqlite can also bind UInt128 parameters, stored as a zero-padded 39-digit text; reading UInt128 from data readers is not yet supported.

var blogs = await context.Blogs
    .Select(b => new
    {
        b.Name,
        Posts = string.Join(
            ", ",
            b.Posts.OrderByDescending(p => p.Id).Select(p => p.Title))
    })
    .ToListAsync();

Azure Cosmos DB

  • Complex types: fully supported, embedded as nested JSON objects (or arrays for collections), with queries, inserts and updates. They have value semantics and no identity, so they often fit better than owned types.
  • Indexes and indexing policy: you can disable automatic indexing, exclude paths, and define single-property, composite, vector and full-text indexes, including through complex types and complex collections.
  • Transactional batches: used by default (AutoTransactionBehavior: Auto, Never for the pre-11 behavior, Always which requires a single batch).
  • Bulk execution: enabled with BulkExecutionEnabled() to improve throughput when saving many entities.
  • Session tokens: managed manually with SessionTokenManagementMode, useful with multiple instances and round-robin load balancing.
  • Modernized JSON serializer: the provider uses System.Text.Json instead of Newtonsoft.Json; the __jObject shadow property is removed and unmapped JSON properties are no longer preserved on round-trip (breaking change).
  • Undefined values in projections: now always throw InvalidOperationException; use IsDefined or CoalesceUndefined.
modelBuilder.Entity<Order>(b =>
{
    b.HasAutomaticIndexing()
        .Except("/InternalNotes/?");
    b.HasIndex(o => new { o.CustomerId, o.OrderDate });
});
options => options.SessionTokenManagementMode(SessionTokenManagementMode.SemiAutomatic)

var sessionToken = context.Database.GetSessionToken();
context.Database.UseSessionToken(sessionToken);
var results = await context.Entities
    .Where(x => EF.Functions.IsDefined(x.Associate!.NestedAssociate!.Id))
    .Select(x => new { x.Associate!.NestedAssociate!.Id })
    .ToListAsync();

Migrations and tooling

  • Excluding foreign keys from migrations: the relationship stays in the EF model (queries, change tracking) but the constraint isn't created; the index on the column remains. Useful for legacy databases or data synchronization.
  • Latest migration ID in the model snapshot: if two developers create migrations on divergent branches, merging produces a conflict that flags the divergence.
  • Create and apply in one step: dotnet ef database update --add (-Add in PowerShell) scaffolds the migration, compiles it with Roslyn and applies it, useful for .NET Aspire and containers; the files are still saved to disk.
  • Connection and offline: migrations remove and database drop accept --connection; migrations remove --offline skips the database connection (can't be combined with --force).
  • Configuration file: .config/dotnet-ef.json provides default values (project, startup project, framework, context...); command-line options take precedence.
  • -NoBuild for Add-Migration and Update-Database in the Package Manager Console.
  • Wildcard context: --context "*" for migrations list, migrations script, database update and database drop.
  • The tool writes logging and status to standard error, reserving standard output for the actual result; an analyzer warns when ToAsyncEnumerable is used instead of AsAsyncEnumerable.
modelBuilder.Entity<Blog>()
    .HasMany(e => e.Posts)
    .WithOne(e => e.Blog)
    .HasForeignKey(e => e.BlogId)
    .ExcludeForeignKeyFromMigrations();
dotnet ef database update InitialCreate --add
dotnet ef migrations remove --offline
dotnet ef migrations list --context "*"
{
  "project": "src/App.Infrastructure",
  "startupProject": "src/App.Api",
  "framework": "net11.0",
  "context": "AppDbContext"
}

Sources


ASP.NET Core 11: everything that's new

ASP.NET Core 11 ships with .NET 11 and brings a long list of changes across Blazor, SignalR, minimal APIs, OpenAPI, authentication, Kestrel and tooling. This guide walks through them area by area, following Microsoft's official release notes. Where a feature is experimental or opt-in, we say so.

Blazor: components and forms

  • DisplayName<TValue> shows a property's name from [Display] (recommended, and it enables localization) or [DisplayName], falling back to the property name.
  • BasePath: the <BasePath /> component renders the <base href> tag automatically in Blazor Web Apps.
  • Relative navigation: the RelativeToCurrentUri parameter (default false) on NavigateTo and NavLink resolves URIs against the current page path.
  • GetUriWithFragment: a NavigationManager extension that builds URIs with hash fragments without allocations.
  • EnvironmentView: conditional rendering by hosting environment through Include and Exclude, case-insensitive.
  • Validation: static SSR forms get client-side validation without a server round trip (on by default with DataAnnotationsValidator), and forms support async validators (AsyncValidationAttribute, IAsyncValidatableObject, IsValidationPending).
  • MathML elements are created with the correct namespace during interactive rendering.
  • Analyzer BL0010 recommends InvokeVoidAsync over InvokeAsync<object> for JavaScript functions that return nothing.
  • IComponentPropertyActivator customizes how [Inject] properties are populated, with keyed-service, Hot Reload and trimming support.

Blazor: state, session and caching

  • TempData in static SSR, ideal for flash messages and the POST-Redirect-GET pattern, with [SupplyParameterFromTempData].
  • Session in static SSR via AddSession/UseSession and [SupplyParameterFromSession]; unlike TempData, values are not cleared after reading. The session cookie is now issued before streaming starts.
  • CacheView caches the rendered markup of a component subtree during static SSR (for example with VaryByQuery and ExpiresAfter) and replays it without instantiating the child components.
  • Server culture: client-side prerendering preserves the server's culture; opt out with WebAssemblyComponentsOptions.UseCultureFromServer = false.
  • Antiforgery: app.UseAntiforgery() is now optional in Blazor Web Apps because CSRF protection is on by default; the call no longer appears in the template.

Blazor: Virtualize, QuickGrid and circuits

  • Virtualize no longer assumes equal item heights and adapts to measured sizes; OverscanCount changes from 3 to 15. The new AnchorMode (None, Start, End) controls behavior at the list edges, while InitialItemIndex and ScrollToItemAsync open and scroll the list to a specific item. It is also compatible with strict CSP because it no longer writes inline styles.
  • QuickGrid: pagination and sorting can live in the query string (?page=2&sort=Name&direction=asc), giving shareable links and working in static SSR without JavaScript; QueryParameterNameOptions renames the parameters and tells several grids on one page apart. It adds OnRowClick and exposes InitialItemIndex, ScrollToItemAsync, AnchorMode and ItemComparer (the last two experimental, ASP0030). Renaming a column Title breaks previously saved URLs.
  • Circuits: Circuit.RequestCircuitPauseAsync lets the server ask for a graceful pause (deployments, instance draining); the opt-in Microsoft.AspNetCore.Components.Server.AutoPause package pauses a circuit when the tab stays hidden; after an authentication refresh the circuit receives the new ClaimsPrincipal without reconnecting.
  • ConfigureConnection on ServerComponentsEndpointOptions configures the SignalR connection options; WithBrowserOptions and ConfigureBrowser configure client startup from server-side C#.

Blazor WebAssembly, templates and AI

  • IHostedService and environment variables in IConfiguration; component metrics and tracing when the runtime has metrics support enabled.
  • Gateway: Microsoft.AspNetCore.Components.Gateway replaces the DevServer for standalone WebAssembly apps and makes the inspectUri property unnecessary.
  • Smaller output: OTEL and Hot Reload code is trimmed away in apps that do not use them.
  • Templates: blazorwebworker (renamed, with InvokeVoidAsync, cancellation and timeout), blazor-wasm-servicedefaults for Aspire, container support in the Blazor Web App template, the mcpserver template bundled in the SDK, and a NavMenu without inline JavaScript.
  • Experimental AI components (Microsoft.AspNetCore.Components.AI): streaming chat, content blocks (RichContentBlock, FunctionApprovalBlock and others) and human approval of tool actions.
  • The release notes list no Blazor Hybrid changes yet.

SignalR and gRPC

SignalR connections can refresh authentication without dropping when the token expires: the server exposes a /refresh endpoint and you enable it per hub with EnableAuthenticationRefresh; the .NET and TypeScript clients refresh automatically and offer RefreshAuthenticationAsync. The client can also cancel regular, non-streaming hub invocations by passing a CancellationToken to InvokeAsync. On gRPC, the Microsoft.AspNetCore.Grpc.Swagger package is deprecated.

Minimal APIs, validation and C# unions

  • Endpoint filters run even when parameter binding fails; in Development, set RouteHandlerOptions.ThrowOnBadRequest = false.
  • The [ShortCircuit] attribute runs an endpoint right after routing, including on MVC controllers.
  • End-to-end async validation in minimal APIs and built-in localization for Microsoft.Extensions.Validation (AddLocalization plus AddValidation); ValidatableTypeAttribute and SkipValidationAttribute are no longer experimental.
  • C# union types are supported wherever System.Text.Json is used; in OpenAPI they are described with anyOf.

OpenAPI

OpenAPI generation describes binary responses (FileContentResult as type: string, format: binary, and likewise the file-stream results), recognizes the HTTP QUERY method, allows several Produces calls for the same status code, maps [Obsolete] to deprecated: true and follows ASP.NET Core behavior more closely for enums and arrays. Generated documents now target OpenAPI 3.2 by default (adjustable with OpenApiVersion), with itemSchema for Server-Sent Events. The OpenApiGenerationEnvironment MSBuild property selects the environment used for build-time generation.

Authentication and authorization

  • ASP.NET Core Identity uses TimeProvider, making expirations and lockouts testable.
  • Passkey names are inferred from the authenticator's AAGUID (Google Password Manager, iCloud Keychain, Windows Hello, 1Password, Bitwarden).
  • dotnet user-jwts create --file app.cs works with file-based apps.
  • IAuthorizationRequirementData attributes now apply to SignalR hubs, MVC controllers and AuthorizeView/AuthorizeRouteView as well, with AuthorizationPolicy.CombineAsync as the shared implementation.
  • Negotiate on Kestrel uses TLS channel binding; the token is also readable through ITlsConnectionFeature.TryGetChannelBindingBytes, and on HTTP.sys HttpAuthenticationHardeningLevel controls extended protection.
  • Experimental support for Device Bound Session Credentials (package Microsoft.AspNetCore.Authentication.DeviceBoundSessions, prerelease throughout .NET 11).

Kestrel, performance and observability

  • The HTTP/1.1 parser no longer throws for malformed requests; the notes cite a 20-40% throughput improvement in scenarios with lots of malformed traffic. HTTP/3 starts processing requests without waiting for the control stream.
  • RequestHeadersTimeout now covers fragmented HTTP/2 and HTTP/3 trailer headers.
  • New TLS diagnostics: ITlsHandshakeFeature.Exception and ListenOptions.UseTlsClientHelloListener (the old callback is obsolete).
  • Zstandard compression for responses and requests, on by default; Vary: Accept-Encoding is always emitted.
  • Native OpenTelemetry tracing: subscribe to the Microsoft.AspNetCore source, no instrumentation library needed.
  • Shared-framework libraries are built with runtime-async; FixedWindowRateLimiter reports an accurate Retry-After; pooling reduces allocations in the HTTP logging middleware.
  • The new IOutputCachePolicyProvider interface, and automatic trust of development certificates in WSL with dotnet dev-certs https --trust.

Before upgrading, check the .NET breaking-changes articles: a few items, such as QuickGrid query parameter names and the obsolete TLS callback, need small adjustments.

Sources


What's new in .NET MAUI for .NET 11

In .NET 11, the focus of .NET MAUI is product quality. The framework still ships as a .NET workload plus several NuGet packages, which makes it easy to pin a project to a specific version and to try unreleased builds. Here is everything listed on the official page, grouped by area.

Runtime: CoreCLR by default

CoreCLR becomes the default runtime on every MAUI platform for projects targeting .NET 11, while NativeAOT is available as an opt-in publishing alternative. Unifying the runtime benefits debugging, profiling, Hot Reload, app size and performance. On Android, Release builds use composite partial ReadyToRun; on iOS and Mac Catalyst, CoreCLR uses composite partial ReadyToRun in Debug and composite full ReadyToRun in Release, with the interpreter always enabled for code that is not precompiled.

Controls

  • Material 3 on Android: the handlers for ImageButton, DatePicker, Entry and Slider adopt Material 3 styling; the helper types are public so you can subclass them in handler customizations.
  • BoxView.Fill: a Brush property enabling linear and radial gradients; when set it takes priority over Color.
  • LongPressGestureRecognizer: configurable duration, movement threshold, GestureState and Command binding.
  • Map: pin clustering (IsClusteringEnabled, ClusterClicked), custom pin icons via ImageSource, JSON styling on Android (MapStyle), events such as MapLongClicked and UserLocationChanged, clicks on Circle/Polygon/Polyline, element IsVisible and ZIndex, animated MoveToRegion and MapSpan.FromLocations. On Windows the map is now backed by Azure Maps (token via UseMapServiceToken), with some features, such as user location and shapes, unsupported.
  • Windows: CollectionView uses the CollectionView2 handler by default (revert with UseWindowsCollectionView2Handler set to false).
  • Handlers on Apple and Android: Shell on Android uses the handler-based architecture; NavigationPage, TabbedPage and FlyoutPage on iOS and Mac Catalyst move to the new handlers. For NavigationPage the timing of Appearing changes (use NavigatedTo) and secondary toolbar items go to an overflow menu. The renderers remain as a manual fallback.
  • TabbedPage badges with BadgeText, BadgeColor and BadgeTextColor. SwipeItem gains IconColor and TextColor, and non-font images keep their original colors.
  • HybridWebView: JavaScript-to-.NET invocation with source-generated JSON metadata, compatible with NativeAOT and full trimming. BlazorWebView: StaticContentCacheControlProvider caches local static content.
  • The optional Microsoft.Maui.Controls.Compatibility package is no longer built or shipped, and the Color record is sealed.

Navigation, animation and accessibility

Shell routes registered with Routing.RegisterRoute can contain path parameters (route templates, inspired by ASP.NET Core and Blazor routing) with required, optional, defaulted, constrained and catch-all segments; for now they require absolute navigation. The ...ToAsync animation methods accept a CancellationToken, and the non-Async variants are obsolete. For accessibility, Windows layouts create MauiLayoutAutomationPeer instances when they expose automation information, and you can set the back button's spoken label with BackButtonAccessibilityLabel (NavigationPage) and AccessibilityLabel (Shell's BackButtonBehavior).

Platform features

  • Passkeys: the Passkeys class drives the WebAuthn/FIDO2 ceremony through the platform authenticator (CreateAsync, AssertAsync); verification remains the server's job.
  • MediaPickerOptions.SaveToGallery, recovery of MediaPicker results on Android after process recreation, GeolocationListeningRequest.MinimumDistance and MSL altitude on Android API 34+.
  • Window.StatusBarTheme for status bar icons, and MauiAndroidSystemBarsUseMauiChrome to use MAUI chrome colors in Android system bars.
  • Windows AppInstance activation through OnAppInstanceActivated, useful for single-instance apps.
  • MonochromeFile for Android adaptive icons, dark-mode splash screens (DarkFile, DarkColor, DarkTintColor) and ResizeQuality for image resizing.
  • Permissions.PostNotifications is implemented on iOS, and an IPermissions abstraction is available through Permissions.Current.
  • CSS support is fully trimmable: without stylesheets it is removed at publish. New InvalidateStyle and InvalidateVisualStates APIs.

XAML and Hot Reload

  • The x:Code directive for inline C# in XAML (requires EnablePreviewFeatures).
  • Implicit XAML namespace declarations are on by default, compiled bindings work correctly inside DataTemplate, and invalid x:DataType values now produce diagnostics.
  • Lazy ResourceDictionary loading: the notes cite up to roughly an 8x improvement in initializing large dictionaries.
  • RelativeSource bindings with an AncestorType compile to AOT-safe bindings.
  • XAML Incremental Hot Reload applies edits to every live instance of pages and controls; it is on by default in Debug and can be disabled with EnableMauiIncrementalHotReload set to false.

Testing and command-line tooling

New test project templates cover Android, iOS, tvOS, macOS and Mac Catalyst (androidtest, iostest, tvostest, macostest, maccatalysttest); they use Microsoft.Testing.Platform and run with dotnet test. dotnet run prompts for the target framework and device when needed, and dotnet watch works on Android and iOS (iOS needs <MtouchLink>None</MtouchLink>).

.NET for Android and iOS

  • Android: minimum API 24 (Android 7.0) instead of 21; x86 is not supported, arm32 is. Faster builds and smaller packages, optional full ReadyToRun via MauiEnableFullReadyToRun; JavaFinalize() is obsolete. NativeAOT is experimental.
  • Apple: iOS, tvOS and Mac Catalyst 18.2, macOS 15.2, Xcode 26.4, HTTP digest authentication in NSUrlSessionHandler, Apple Intelligence APIs, the NativeAOT registrar by default, dSYM files generated by default and headers/modules stripped from bundled frameworks (StripFrameworkHeaders).

Installing .NET MAUI

According to the official installation page, you need Visual Studio 2022 17.12 or later, or Visual Studio Code with the .NET MAUI extension; building for iOS and macOS requires a Mac compatible with Xcode. With the .NET SDK installed, you can add the workload manually with dotnet workload install maui (on Linux, maui-android) and check it with dotnet workload list. Useful links: the .NET MAUI installation guide, the .NET 11 download page and the .NET releases on GitHub.

Sources


.NET MAUI architecture: layers, handlers and single project

.NET MAUI (.NET Multi-platform App UI) is Microsoft's framework for building native mobile and desktop apps with C# and XAML from a single shared code base. It is open source and is the evolution of Xamarin.Forms, extended from mobile to desktop, with UI controls rebuilt from the ground up for performance and extensibility. This article explains how it is put together: layers, handlers, single project, startup, lifecycle, dependency injection and binding, and where it sits in the .NET 11 runtime.

The architectural layers

.NET MAUI unifies the Android, iOS, macOS and Windows APIs into a single API while still giving deep access to every native platform. Underneath, .NET provides the platform-specific frameworks: .NET for Android, .NET for iOS, .NET for Mac Catalyst and the Windows UI 3 (WinUI 3) library. They all share the Base Class Library (BCL), which hides platform details and depends on the .NET runtime.

The documentation describes three ways your code interacts with the stack:

  1. your app code mostly talks to the .NET MAUI controls and API layer;
  2. that layer directly consumes the native platform APIs;
  3. when needed, app code can also call platform APIs directly.

The target platforms are Android, iOS, macOS and Windows. On macOS, apps use Mac Catalyst, Apple's solution that brings a UIKit-based iOS app to the desktop and can be augmented with AppKit; on Windows, WinUI 3. The single-project page also lists Tizen among the platforms. Building for iOS and macOS requires a Mac.

Controls, virtual views and handlers

Every cross-platform control has an interface representation (for example IButton for Button); controls implementing these interfaces are called virtual views. Handlers map them to the native controls on each platform (native views), instantiate the native view and translate the cross-platform API into the native one. An example from the official page: on iOS a Button maps to a UIButton, on Android to a MaterialButton.

Handlers are reached through the control's interface, so the control never has to reference its handler and the handler never has to reference the control. Each handler exposes the native view through PlatformView and the cross-platform control through VirtualView.

Mappers and the handler lifecycle

The key concept is the mapper. A property mapper is a dictionary mapping the control's properties to the actions to run when they change; a command mapper does the same for commands sent to the native view (here a "command" is an instruction with optional data, not an ICommand). This keeps native views decoupled from controls, removes the need to subscribe to events, and makes customization easy because you can modify mappers without subclassing. Note that handlers are global: customizing one changes every control of that type in the app.

All handler-based controls raise two events: HandlerChanging (a handler is about to be created or removed, so this is the moment to unwire native events) and HandlerChanged (the native control exists and property values have been applied), with the overridable OnHandlerChanging and OnHandlerChanged methods.

Single project

The single project abstracts platform-specific experiences into one project, enabled by multi-targeting and SDK-style projects. It offers:

  • one project for Android, iOS, macOS, Tizen and Windows, with simplified debug target selection;
  • shared resources in the Resources folder, with dedicated build actions: MauiIcon, MauiFont, MauiImage, MauiSplashScreen, MauiAsset, MauiCss. Images are source files from which the resolutions each platform needs are generated at build time;
  • a single manifest for title, ID and version, merged with the native data at build time;
  • the Platforms folder, with one subfolder per platform: only the code for the target platform is built. Multi-targeting combines with partial classes and methods or with conditional compilation (#if ANDROID, #elif IOS, #elif WINDOWS);
  • a single cross-platform entry point.

MauiProgram and the builder

When each platform starts, it calls the CreateMauiApp method of the static MauiProgram class, which returns a MauiApp. At a minimum it must provide the app to run:

public static class MauiProgram
{
    public static MauiApp CreateMauiApp()
    {
        var builder = MauiApp.CreateBuilder();
        builder.UseMauiApp<App>();
        return builder.Build();
    }
}

The MauiAppBuilder is the place for configuration: fonts via ConfigureFonts, services through the Services property, logging, and lifecycle events with ConfigureLifecycleEvents. The App class derives from Application and, in the latest version of the documentation, creates the window by overriding CreateWindow (for example new Window(new AppShell())); AppShell describes the app's visual hierarchy through Shell.

Lifecycle

A MAUI app moves through four states: not running, running, deactivated and stopped. The Window class raises cross-platform events for the transitions: Created, Activated, Deactivated, Stopped, Resumed and Destroying, mapped to native events (for example Android's OnResume or iOS's OnActivated for Activated). On Stopped the documentation suggests disconnecting from long-running processes and canceling pending requests; on Resumed, re-subscribing to events and refreshing the visible page; on Destroying, removing subscriptions to the native window. To react to native events, register delegates through ConfigureLifecycleEvents.

Dependency injection

.NET MAUI has built-in support for Microsoft.Extensions.DependencyInjection to manage the creation of views, view models and services. Registration normally happens in CreateMauiApp through builder.Services with AddSingleton, AddTransient or AddScoped; the types are handed to the container when Build() is called. The page warns that in non-Blazor MAUI apps AddScoped has no natural scope boundary and behaves like a singleton: use AddTransient for pages and view models, and AddSingleton for shared services.

Resolution is automatic in Shell apps through constructor injection (for example a page receiving its view model), including pages registered with Routing.RegisterRoute. Otherwise you use explicit resolution through Handler.MauiContext.Services.

Binding and MVVM

Model-View-ViewModel separates the XAML view, the data (model) and the view model acting as intermediary; view and view model are usually connected by data bindings, and the view's BindingContext is typically a view model instance. A BindingContext set on an element is inherited by its children. One useful detail: .NET MAUI marshals binding updates to the UI thread, so view model properties can be updated from any thread. Only BindableProperty properties are bindable.

MAUI and Blazor Hybrid

Blazor Hybrid support is built into .NET MAUI through the BlazorWebView control, which can be added to any page and pointed at the root of the Blazor app. Razor components run natively in the .NET process (no browser, no WebAssembly) and render the UI into an embedded web view, with full access to native device capabilities. This lets you reuse one set of web UI components across mobile, desktop and web. The control exposes configuration events such as BlazorWebViewInitializing and BlazorWebViewInitialized; on Windows, end users need the WebView2 runtime.

Where it fits in the .NET 11 runtime

In .NET 11, MAUI ships as a .NET workload plus NuGet packages, and CoreCLR is the default runtime on every MAUI platform for projects targeting .NET 11, with NativeAOT as an optional publishing alternative. This updates the picture in the "What is .NET MAUI" page, which still mentions Mono for Android, iOS and macOS. The single project remains the foundation, but in .NET 11 handlers become even more central: Shell on Android and NavigationPage, TabbedPage and FlyoutPage on iOS and Mac Catalyst move to the handler-based architecture.

Sources


Comments (0)

No comments yet.

Leave a comment