loading experience

Guide

Guide to C# 14 and .NET 10: what is new in the language and the runtime

Guide to C# 14 and .NET 10: what is new in the language and the runtime

The overview of .NET 10 LTS, runtime performance, Native AOT, file-based apps, System.Text.Json, post-quantum cryptography and what is new in C# 14 (extension members, the field keyword, null-conditional assignment, Span), with best practices on collection expressions, primary constructors, pattern matching and async/await.

In this guide

  1. .NET 10: an overview of the new LTS release
  2. Performance in .NET 10: what improves in the runtime
  3. Native AOT in .NET 10: instant startup and compact binaries
  4. .NET 10: running a single C# file with dotnet run
  5. System.Text.Json in .NET 10: stricter, safer JSON
  6. Post-quantum cryptography in .NET 10: ML-KEM and ML-DSA
  7. C# 14: extension members explained with examples
  8. C# 14: the field keyword in properties
  9. C# 14: null-conditional assignment with ?.
  10. Span and ReadOnlySpan in C# 14: implicit conversions
  11. Collection expressions in C#: one syntax for every collection
  12. Primary constructors in C#: when to use them and when not to
  13. Pattern matching in modern C#: records, switch and list patterns
  14. async/await in C#: best practices, Task and ValueTask

.NET 10: an overview of the new LTS release

.NET 10 is an LTS (Long Term Support) release: it receives updates and security fixes for three years. For business applications it is the natural foundation for upcoming projects.

Official support windows: .NET 8 and 9 until November 2026, .NET 10 until November 2028.
Official support windows: .NET 8 and 9 until November 2026, .NET 10 until November 2028.

Main new features

  • C# 14: extension members, the field keyword, null-conditional assignment and implicit conversions to Span.
  • Performance: the JIT optimises loops and virtual calls better and can stack-allocate small objects that do not escape the method.
  • File-based apps: a single .cs file runs with dotnet run, no project needed.
  • Security: post-quantum cryptography algorithms such as ML-KEM and ML-DSA.
  • ASP.NET Core 10: validation in Minimal APIs, OpenAPI 3.1, passkeys in Identity, Blazor improvements.
  • EF Core 10: LeftJoin and RightJoin operators, named query filters, vector search on SQL Server.

How to upgrade a project

In most cases you only need to change the target framework and update packages to version 10:

<PropertyGroup>
  <TargetFramework>net10.0</TargetFramework>
  <Nullable>enable</Nullable>
  <ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>

After upgrading, build with warnings enabled, read the breaking-change notes and run the full test suite. Libraries that depend on third-party packages must be checked one by one: that is where surprises hide.

When to migrate

If you are on .NET 8, which is also LTS, you have time to plan calmly. If you are on releases that are no longer supported, migrating to .NET 10 is the safest choice: a single jump and three years of support ahead.


Performance in .NET 10: what improves in the runtime

Every .NET release brings "free" performance improvements: you update the target framework and existing code becomes faster. .NET 10 is no exception.

Each step reduces allocations or indirect calls in existing code.
Each step reduces allocations or indirect calls in existing code.

Fewer heap allocations

The JIT is better at analysing whether an object "escapes" the method that creates it. When a small object, a fixed-size array or a delegate stays local, the JIT can allocate it on the stack instead of the heap: less work for the garbage collector and fewer pauses.

More direct calls

Devirtualisation turns calls through interfaces into direct calls when the concrete type is known, opening the way to inlining. In .NET 10 this also applies to many array interface methods, which are heavily used in foreach loops over collections.

Loops and modern instructions

The compiler reorganises loops better, removes redundant bounds checks and takes advantage of the vector instructions of recent CPUs, including AVX10 extensions on x64 and SVE instructions on Arm64.

How to check it on your code

Do not trust feelings: measure. A repeatable benchmark before and after the upgrade tells you exactly how much you gain.

[MemoryDiagnoser]
public class SumBenchmark
{
    private readonly int[] _data = Enumerable.Range(0, 10_000).ToArray();

    [Benchmark]
    public int Sum()
    {
        var total = 0;
        foreach (var n in _data) total += n;
        return total;
    }
}

Run the same benchmark with net8.0 and net10.0 as targets and compare times and allocations: it is the most honest way to decide whether, and how much, migrating pays off.


Native AOT in .NET 10: instant startup and compact binaries

With Native AOT the application is compiled to machine code at publish time. No installed runtime is needed, startup is almost instant and memory usage drops: ideal for container services, serverless functions and command-line tools.

Native AOT trades runtime flexibility for fast startup and low memory.
Native AOT trades runtime flexibility for fast startup and low memory.

Enabling it

<PropertyGroup>
  <PublishAot>true</PublishAot>
</PropertyGroup>
dotnet publish -c Release -r linux-x64

What changes in the code

The AOT compiler must know in advance all the code that will run. That is why dynamic reflection, loading assemblies at runtime and generating code on the fly are restricted. The compiler reports this with specific warnings: take them seriously.

For JSON serialisation you use compile-time code generation:

[JsonSerializable(typeof(Order))]
[JsonSerializable(typeof(List<Order>))]
internal partial class AppJsonContext : JsonSerializerContext { }

var json = JsonSerializer.Serialize(order, AppJsonContext.Default.Order);

ASP.NET Core and AOT

Minimal APIs support Native AOT; the dedicated template uses WebApplication.CreateSlimBuilder, which includes only the essential services. MVC and Razor Pages, on the other hand, are not AOT compatible.

When not to use it

Applications with plugins loaded at runtime, ORMs or reflection-based libraries that are not compatible, or projects where startup time is not an issue: in those cases traditional publishing remains the simpler choice.


.NET 10: running a single C# file with dotnet run

To try an idea in C# you always needed a project: folder, .csproj file, structure. With .NET 10 a single file is enough: dotnet run app.cs compiles and runs it.

A single file grows into a full project without starting over.
A single file grows into a full project without starting over.

The first script

// hello.cs
Console.WriteLine($"Hello from .NET {Environment.Version}");
dotnet run hello.cs

Packages and settings in the file

Directives starting with #: replace the project file: you can add NuGet packages, change SDK or set build properties.

#:package Humanizer@2.14.1

using Humanizer;

var days = TimeSpan.FromDays(3);
Console.WriteLine(days.Humanize());

For a small web API you can declare the web SDK with #:sdk Microsoft.NET.Sdk.Web and write a Minimal API in the same file.

When the file grows

When the script becomes a real application, the dotnet project convert command turns it into a full project, keeping the packages and settings declared in the directives.

Practical uses

  • Maintenance and automation scripts instead of batch or PowerShell files.
  • Quick prototypes and library experiments.
  • Teaching examples: a single file to share.

System.Text.Json in .NET 10: stricter, safer JSON

System.Text.Json is the JSON serializer built into .NET. In .NET 10 it adds options designed mainly for those who receive JSON from external sources and want to be strict.

With strict options, ambiguous documents stop before becoming data.
With strict options, ambiguous documents stop before becoming data.

Rejecting duplicate properties

A JSON document with the same property repeated twice is ambiguous: which value wins? Some attacks exploit exactly the difference in interpretation between systems. You can now ask the serializer to reject such documents.

var options = new JsonSerializerOptions
{
    AllowDuplicateProperties = false
};

// throws JsonException: "amount" appears twice
var json = "{ \"amount\": 10, \"amount\": 1000 }";
var p = JsonSerializer.Deserialize<Payment>(json, options);

A ready-made strict profile

JsonSerializerOptions.Strict bundles the strictest settings: no unknown properties, no duplicates, respect for nullable types and required constructor parameters. It is a good starting point for public APIs.

var order = JsonSerializer.Deserialize<Order>(json, JsonSerializerOptions.Strict);

Reading directly from PipeReader

High-performance applications such as ASP.NET Core read incoming data through a PipeReader. In .NET 10 the serializer can deserialise directly from this source, avoiding intermediate copies in memory.

Tips

  • Use source generation (JsonSerializerContext) for better performance and Native AOT compatibility.
  • Define shared options once and reuse them: creating them each time is expensive.
  • Prefer strict settings for incoming data; you can be more lenient for outgoing data.

Post-quantum cryptography in .NET 10: ML-KEM and ML-DSA

Future quantum computers could break RSA and elliptic-curve cryptography. NIST has standardised new algorithms that resist these attacks, and .NET 10 makes them available in System.Security.Cryptography.

First you learn where cryptography is used, then you replace it step by step.
First you learn where cryptography is used, then you replace it step by step.

The algorithms

  • ML-KEM: key exchange (encapsulation), to establish a shared secret.
  • ML-DSA: lattice-based digital signature.
  • SLH-DSA: hash-based digital signature, very conservative.

Checking support

The implementations rely on the operating system (Windows cryptographic libraries or OpenSSL on Linux), so before using them you check whether the platform supports them.

using System.Security.Cryptography;

if (MLKem.IsSupported)
{
    using MLKem key = MLKem.GenerateKey(MLKemAlgorithm.MLKem768);
    Console.WriteLine($"Key generated: {key.Algorithm.Name}");
}
else
{
    Console.WriteLine("ML-KEM is not available on this platform.");
}

"Harvest now, decrypt later"

Why worry today? Because an attacker can record encrypted traffic today and decrypt it years from now. For data that must stay confidential for a long time, such as health data, contracts or trade secrets, the transition must be planned now.

A gradual transition

The recommended path is the hybrid approach, which combines a classical algorithm and a post-quantum one: security holds even if one of the two turned out to be weak. The first practical step is an inventory of where your application uses cryptography, so you know what will have to change.


C# 14: extension members explained with examples

Extension methods have existed since C# 3, but they only let you add methods. C# 14 introduces extension blocks, which also let you define extension properties and static extension members on an existing type.

An extension block groups every member that extends the same type.
An extension block groups every member that extends the same type.

The new syntax

Inside a static class you declare an extension block with the "receiver", that is the type being extended. Every member of the block can use that receiver.

public static class StringExtensions
{
    extension(string text)
    {
        // extension property
        public bool IsBlank => string.IsNullOrWhiteSpace(text);

        // extension method, as before but without "this"
        public string Truncate(int max) =>
            text.Length <= max ? text : text[..max] + "...";
    }
}

var title = "Introduction to .NET 10";
Console.WriteLine(title.IsBlank);       // False
Console.WriteLine(title.Truncate(12));  // Introduction...

Static extension members

By omitting the parameter name you extend the type itself, not an instance: you can add "static" methods or properties to a type you do not control.

public static class GuidExtensions
{
    extension(Guid)
    {
        public static Guid FromText(string value) =>
            Guid.TryParse(value, out var g) ? g : Guid.Empty;
    }
}

var id = Guid.FromText("not-valid"); // Guid.Empty

Compatibility

Old extension methods with this keep working and can live alongside the new blocks. There is nothing to rewrite: adopt extension blocks when you need properties or static members, or when you want to group several extensions of the same type.

Tips

  • Use extension properties for derived information without side effects.
  • Avoid "stuffing" system types with dozens of extensions: prefer dedicated namespaces.
  • Remember that an instance member always takes precedence over an extension with the same name.

C# 14: the field keyword in properties

Auto-properties are handy until you need a little logic: at that point you had to declare a private field and write full get and set accessors. C# 14 introduces the field keyword, which represents the backing field generated by the compiler.

The field keyword removes the hand-written backing field.
The field keyword removes the hand-written backing field.

Before and after

// Before
private string _name = "";
public string Name
{
    get => _name;
    set => _name = value?.Trim() ?? "";
}

// With C# 14
public string Name
{
    get;
    set => field = value?.Trim() ?? "";
} = "";

Typical use cases

  • Normalisation: whitespace, casing, formats.
  • Validation: throw an exception if the value is not acceptable.
  • Change notification in MVVM apps.
public int Quantity
{
    get;
    set
    {
        ArgumentOutOfRangeException.ThrowIfNegative(value);
        field = value;
    }
}

Watch out for names

If a class already has a member called field, the keyword takes precedence inside accessors. In those cases you can use @field or this.field to refer to the existing member; the compiler reports ambiguities.

The result is shorter code, with the logic next to the property and no private fields scattered around the class.


C# 14: null-conditional assignment with ?.

For years the ?. operator has let you read a member only if the object is not null. With C# 14 you can also use it to assign: the assignment happens only if the object exists.

If the receiver is null, the right-hand side is not even evaluated.
If the receiver is null, the right-hand side is not even evaluated.

An example

// Before
if (customer is not null)
{
    customer.LastOrder = order;
}

// With C# 14
customer?.LastOrder = order;

If customer is null, the right-hand expression is not evaluated. That is an important detail: if the right side contains an expensive call or one with side effects, it will not run needlessly.

It also works with indexers and compound operators

settings?["theme"] = "dark";
counters?.Total += 1;

Compound assignment operators such as += and -= are allowed; increment and decrement (++ and --) are not.

When to use it

  • To update optional objects, such as a context or a configuration that may be missing.
  • In event handlers and callbacks, where the object may already have been released.

It does not replace good type design: if a value should never be null, declare it non-nullable and let the compiler help you.


Span and ReadOnlySpan in C# 14: implicit conversions

Span<T> and ReadOnlySpan<T> represent a contiguous region of memory without copying it: they are the foundation of high-performance .NET code. C# 14 makes them "first-class citizens" with new implicit conversions.

Implicit conversions bring arrays and strings to span-based APIs.
Implicit conversions bring arrays and strings to span-based APIs.

What changes

An array can be implicitly converted to Span<T> and ReadOnlySpan<T>, and the compiler also considers these conversions when looking up extension methods. The result: extensions written for ReadOnlySpan<T> can be called directly on an array.

public static class SpanExtensions
{
    public static int CountEven(this ReadOnlySpan<int> values)
    {
        var n = 0;
        foreach (var v in values) if (v % 2 == 0) n++;
        return n;
    }
}

int[] numbers = [1, 2, 3, 4, 5, 6];
Console.WriteLine(numbers.CountEven()); // 3, no .AsSpan()

Why it helps

  • You write a single version of the method for arrays, strings and memory slices.
  • You avoid copies: working on a slice with values[2..5] allocates nothing.
  • Libraries can offer span-based overloads, which the compiler prefers automatically.

An example with strings

ReadOnlySpan<char> line = "2026-10-10;order;42";
var first = line.IndexOf(';');
var date = line[..first];          // no new string
Console.WriteLine(date.ToString()); // 2026-10-10

One caveat: spans live only on the stack and cannot be stored in class fields or used across await. For those cases there is Memory<T>.


Collection expressions in C#: one syntax for every collection

Collection expressions unify collection creation: the same square-bracket syntax works for arrays, List<T>, Span<T>, HashSet<T> and many other types.

The compiler picks the best way to build each collection.
The compiler picks the best way to build each collection.

Basic syntax

int[] numbers = [1, 2, 3];
List<string> names = ["Anna", "Luca"];
HashSet<char> vowels = ['a', 'e', 'i', 'o', 'u'];
ReadOnlySpan<byte> header = [0x50, 0x4B, 0x03, 0x04];
List<int> empty = [];

The compiler chooses the most efficient way to build each type: for example a span of constants can point directly at the program's data without allocating.

The spread operator

With .. you insert all the elements of another collection:

string[] basic = ["read"];
string[] admin = [.. basic, "write", "delete"];

IEnumerable<int> Even(int max) => [.. Enumerable.Range(0, max).Where(n => n % 2 == 0)];

In method signatures

Collection expressions work wherever the target type is known, including as arguments:

void Notify(IReadOnlyList<string> recipients) { /* ... */ }

Notify(["info@company.com", "support@company.com"]);

Why adopt them

  • Uniform code: changing the collection type does not require rewriting the initialisation.
  • Performance: the compiler optimises construction for each type.
  • Readability: spread replaces many calls to Concat and AddRange.

Primary constructors in C#: when to use them and when not to

Since C# 12, classes can have a primary constructor: parameters are declared next to the class name and are visible throughout the body. They are perfect for services with dependency injection.

Handy for services, to be used with some care.
Handy for services, to be used with some care.

Before and after

// Before
public class OrderService
{
    private readonly IOrderRepository _repo;
    private readonly ILogger<OrderService> _log;

    public OrderService(IOrderRepository repo, ILogger<OrderService> log)
    {
        _repo = repo;
        _log = log;
    }
}

// With the primary constructor
public class OrderService(IOrderRepository repo, ILogger<OrderService> log)
{
    public async Task<Order?> FindAsync(int id)
    {
        log.LogInformation("Looking up order {Id}", id);
        return await repo.GetAsync(id);
    }
}

The pitfall: parameters are not readonly

A primary constructor parameter can be modified inside the class. If you want the guarantee that it does not change, assign it to a readonly field:

public class Cache(TimeSpan duration)
{
    private readonly TimeSpan _duration = duration;
}

Other things to watch

  • Do not use the same parameter both directly and to initialise a field: the compiler warns because two copies of the state would be created.
  • For types that represent data, record types remain the best choice: they generate properties, equality and ToString.
  • If the constructor must validate parameters, validation in a field initialiser works, but for complex logic a classic constructor is clearer.

Pattern matching in modern C#: records, switch and list patterns

Pattern matching has transformed the way conditional logic is written in C#. Combined with record types, it lets you express complex rules in a few readable lines.

Cases are evaluated top-down: the most specific go first.
Cases are evaluated top-down: the most specific go first.

Switch expressions with properties

public record Order(decimal Total, string Country, bool PremiumCustomer);

decimal Shipping(Order o) => o switch
{
    { PremiumCustomer: true }           => 0m,
    { Country: "IT", Total: >= 50m }    => 0m,
    { Country: "IT" }                   => 5.90m,
    { Total: >= 150m }                  => 9.90m,
    _                                   => 19.90m
};

Rules read from top to bottom and the compiler warns you if a case can never be reached.

Relational and logical patterns

string Band(int age) => age switch
{
    < 0              => throw new ArgumentOutOfRangeException(nameof(age)),
    < 18             => "minor",
    >= 18 and < 65   => "adult",
    _                => "senior"
};

List patterns

List patterns match the shape of an array or list: first element, last, length, slices.

string Describe(string[] args) => args switch
{
    []                       => "no command",
    ["help"]                 => "show help",
    ["copy", var from, var to] => $"copy {from} to {to}",
    ["log", .. var rest]     => $"log with {rest.Length} options",
    _                        => "unknown command"
};

Tips

  • Put the most specific cases before the generic ones.
  • Avoid overly long switch expressions: beyond a dozen cases consider a rules table.
  • With closed hierarchies of records, the compiler helps you not forget cases.

async/await in C#: best practices, Task and ValueTask

Asynchronous code makes applications responsive and scalable, but a few recurring mistakes can cause hangs, lost exceptions or worse performance than synchronous code.

Each layer awaits the next and passes the cancellation token along.
Each layer awaits the next and passes the cancellation token along.

Rule 1: async all the way

Blocking a Task with .Result or .Wait() wastes threads and, in some contexts, causes deadlocks. If a method calls asynchronous code, it must become asynchronous too.

// Avoid
var customer = repo.FindAsync(id).Result;

// Correct
var customer = await repo.FindAsync(id);

Rule 2: no async void

An async void method cannot be awaited and its exceptions cannot be caught with a normal try/catch. Use it only for event handlers; in every other case return Task.

Rule 3: pass the CancellationToken along

public async Task<Report> GenerateAsync(int year, CancellationToken ct)
{
    var data = await _repo.LoadAsync(year, ct);
    return await _engine.ProcessAsync(data, ct);
}

That way a web request cancelled by the user really stops the work, instead of continuing to consume resources.

When to use ValueTask

ValueTask avoids an allocation when the result is often already available, for example read from a cache:

public ValueTask<Product?> FindAsync(int id)
{
    if (_cache.TryGetValue(id, out var p))
        return ValueTask.FromResult<Product?>(p); // no allocation

    return new ValueTask<Product?>(LoadFromDatabaseAsync(id));
}

But it comes with rules: a ValueTask is awaited only once and must not be stored for reuse. When in doubt, Task remains the safer choice; use ValueTask only where a measurement proves the benefit.


Comments (0)

No comments yet.

Leave a comment