Skip to content

C# 13 (2024): params collections, the Lock type and ref structs

  • What C# 13 added, which SDK and Visual Studio version it needs, and its support status.
  • How params collections remove hidden array allocations, and the overload change that can break expression trees.
  • What the lock statement does when its target is a System.Threading.Lock, and how to multi-target it.
  • What allows ref struct and ref struct interfaces unlock for span-based generic code.
  • The smaller changes: \e, ^ in initializers, overload resolution priority, ref locals in async methods and partial properties.

C# 13 is the .NET 9 edition of the language: released and stable, but its paired runtime is now out of support.

Item Value
Released November 2024
Paired runtime .NET 9 (STS)
Minimum toolset .NET 9 SDK; Visual Studio 2022 version 17.12
Default for TFM net9.0
LangVersion 13.0 (or 13)
Support today Out of support: .NET 9 support ended November 10, 2026. Microsoft states that C# 13 “is supported only on .NET 9 and newer versions”
Previews in this release The field keyword (finalized in C# 14)

Several features depend on types that first shipped in .NET 9, such as System.Threading.Lock and OverloadResolutionPriorityAttribute.

Feature Weight Mainly for Deep dive
params collections Headline Library code, performance params collections
System.Threading.Lock Headline App and library code This page
allows ref struct and ref struct interfaces Headline Library code, performance Span and ref structs
\e escape Smaller App code This page
^ in object initializers Smaller App code This page
Overload resolution priority Smaller Library code This page
ref locals and unsafe in async methods and iterators Smaller Performance This page
Partial properties and indexers Smaller Source generators Partial properties
field keyword Preview App code C# 14

Create a console app with dotnet new console, replace Program.cs with the sample, and keep the default implicit using directives and <Nullable>enable</Nullable>. If you build with a newer SDK, add <LangVersion>13.0</LangVersion> to see exactly what C# 13 accepts. The samples were compiled with the compiler in .NET SDK 10.0.115 using -langversion:13.0 against the .NET 10 reference assemblies (with NET9_0_OR_GREATER defined, as the SDK does) and run on .NET 10.0.15. The output contains no culture-sensitive values. It is shown under each sample.

Before C# 13, params required an array, so every call such as TotalQuantity(1, 2, 3) allocated an int[], even when the method only read the values once. Library authors who wanted span overloads had to ask callers to build spans by hand.

params accepts any type you can create with a collection expression: Span<T>, ReadOnlySpan<T>, types with a collection initializer or builder, and the interfaces IEnumerable<T>, IReadOnlyCollection<T>, IReadOnlyList<T>, ICollection<T> and IList<T>. For a span parameter, the compiler can store the arguments on the stack and wrap a span around them, which avoids the implicit array allocation. For an interface parameter, the compiler chooses the storage. When both a params span and a params array overload apply to an expanded call, overload resolution prefers the span.

// OrdersPortal sums line quantities and formats order tags.
Console.WriteLine(OrderMetrics.TotalQuantity(1, 2, 3)); // expanded form: binds to the span overload
Console.WriteLine(OrderMetrics.TotalQuantity([4, 5])); // a collection expression also works
int[] fromApi = [6, 7];
Console.WriteLine(OrderMetrics.TotalQuantity(fromApi)); // an existing array binds to the array overload
Console.WriteLine(OrderMetrics.Tags("gift", "express")); // params IEnumerable<string>
static class OrderMetrics
{
// Kept for binary compatibility with callers compiled against older versions.
public static string TotalQuantity(params int[] quantities) => $"array: {Sum(quantities)}";
// C# 13: params on a span. The arguments don't need a heap array.
public static string TotalQuantity(params ReadOnlySpan<int> quantities) => $"span: {Sum(quantities)}";
public static string Tags(params IEnumerable<string> tags) => string.Join("|", tags);
private static int Sum(ReadOnlySpan<int> values)
{
int total = 0;
foreach (int value in values) total += value;
return total;
}
}

Output:

span: 6
span: 9
array: 13
gift|express
  • Expression trees. .NET 9 added more than 60 params ReadOnlySpan<T> overloads, for example to string.Join. A call inside an Expression<...> lambda that used to bind to the array overload now binds to the span overload and fails with “CS8640: Expression tree cannot contain value of ref struct or restricted type” and CS9226, because expression trees can’t contain ref structs. Pass an explicit array in those lambdas.
  • Rebinding is silent elsewhere. Ordinary recompiled calls move to the span overload without a warning. That is usually a free speed-up, but the two overloads must behave identically.
  • params IEnumerable<T> isn’t lazy. The compiler materializes the arguments, so the method can enumerate them more than once, but it can’t stream them.

Don’t add a params span overload to an API that callers use mainly inside expression trees, such as a query provider. Don’t replace a params array with a span in a public library without keeping the array overload: removing it breaks binary compatibility for callers compiled against the old version.

lock (obj) uses System.Threading.Monitor on any object, so a lock is just a convention: nothing in the field’s type says “this is a lock”, and nothing warns when the object is passed around or locked by unrelated code. .NET 9 added System.Threading.Lock, a type whose only job is mutual exclusion. The gain is a field type that documents its purpose, plus a compiler warning (CS9216) when that lock is converted to another type and would silently fall back to Monitor.

If the expression in a lock statement is exactly of type System.Threading.Lock, the compiler calls Lock.EnterScope() and disposes the returned Lock.Scope (a ref struct) to exit, instead of calling Monitor.Enter and Monitor.Exit. You change only the field’s type. The semantics are the familiar ones: a thread can enter the same lock more than once (re-entrancy) and must exit it the same number of times, and IsHeldByCurrentThread reports whether the current thread holds it. Microsoft says the lock and EnterScope patterns “might also have performance benefits” over Enter and Exit, but it doesn’t document the internal reasons, so measure before claiming a gain.

The #if keeps a library that also targets older frameworks compiling: the SDK defines NET9_0_OR_GREATER for .NET 9 and later targets.

var stats = new OrderStats();
Parallel.For(0, 1000, _ => stats.RecordOrder());
Console.WriteLine(stats.Count);
stats.RecordBatch(3);
Console.WriteLine(stats.Count);
sealed class OrderStats
{
#if NET9_0_OR_GREATER
private readonly Lock _gate = new(); // System.Threading.Lock: lock() uses EnterScope()
#else
private readonly object _gate = new(); // older targets: lock() uses Monitor
#endif
public int Count { get; private set; }
public void RecordOrder()
{
lock (_gate)
{
Count++;
}
}
public void RecordBatch(int orders)
{
lock (_gate)
{
for (int i = 0; i < orders; i++)
{
RecordOrder(); // re-entering on the same thread is allowed
}
#if NET9_0_OR_GREATER
Console.WriteLine(_gate.IsHeldByCurrentThread);
#endif
}
}
}

Output:

1000
True
1003
  • Conversions fall back to Monitor. If a Lock is converted to object, an interface or a type parameter T, the lock statement uses Monitor on that object, which doesn’t interact with EnterScope callers. The compiler warns: “CS9216: A value of type ‘System.Threading.Lock’ converted to a different type will use likely unintended monitor-based locking in ‘lock’ statement.” Keep the field private and typed as Lock.
  • Still not async. You can’t await inside a lock block, and if you call Enter and Exit manually in an async method, the code after an await can run on another thread. Use SemaphoreSlim for asynchronous mutual exclusion.
  • Lock ordering still matters. Entering two locks in different orders on different code paths can deadlock, exactly as with Monitor.

Keep object when the lock must be shared with code that uses Monitor directly (for example Monitor.Wait and Monitor.Pulse, which Lock doesn’t offer), or when the code must build for targets earlier than .NET 9 without #if.

Headline feature: allows ref struct and ref struct interfaces

Section titled “Headline feature: allows ref struct and ref struct interfaces”

Generic code couldn’t accept Span<T> or your own ref struct types, and ref structs couldn’t implement interfaces, so span-based helpers had to be written once per type.

The anti-constraint where T : allows ref struct permits ref struct type arguments; the compiler then enforces ref safety rules on every use of T inside the method. A ref struct may implement interfaces, but it can never be converted to the interface type, because that would box it onto the heap. Its interface members are reachable only through a type parameter that allows ref structs, and it must implement every interface member, including those with default implementations.

// OrdersPortal reports on quantities that arrive as spans, without copying them to an array.
ReadOnlySpan<int> quantities = [3, 1, 4, 1, 5];
var summer = new QuantitySummer(quantities);
Console.WriteLine(Report.Describe(summer));
Console.WriteLine(Report.Describe(new ListSummer([2, 2]))); // ordinary types still work
interface ISummer
{
int Total();
}
// C# 13: a ref struct can implement an interface...
ref struct QuantitySummer(ReadOnlySpan<int> values) : ISummer
{
private readonly ReadOnlySpan<int> _values = values;
public int Total()
{
int total = 0;
foreach (int value in _values) total += value;
return total;
}
}
sealed class ListSummer(List<int> values) : ISummer
{
public int Total() => values.Sum();
}
static class Report
{
// ...and be a type argument when the type parameter 'allows ref struct'.
public static string Describe<T>(T summer) where T : ISummer, allows ref struct
=> $"total={summer.Total()}";
}

Output:

total=14
total=4
  • Inside a method whose T allows ref structs, you can’t box T, store it in a field of a class, capture it in a lambda or use it across an await.
  • ISummer summer = new QuantitySummer(...) doesn’t compile; the interface is usable only through the generic parameter.

Most application code benefits indirectly, as the runtime libraries adopt these features. Add allows ref struct to your own generics only when a span-based caller needs it, because it restricts what the generic body can do with T.

The combined sample below covers five smaller changes, each with one OrdersPortal purpose.

using System.Runtime.CompilerServices;
// \e is ESCAPE (U+001B): bold terminal text for urgent orders.
Console.WriteLine("\e[1mURGENT\e[0m".Length);
// ^ (from the end) in an object initializer: the depot is always the last stop.
var route = new DeliveryRoute { Stops = { [^1] = "Depot", [^2] = "Customer B", [^3] = "Customer A" } };
Console.WriteLine(string.Join(" -> ", route.Stops));
// OverloadResolutionPriority: the new span overload wins over the string overload.
Console.WriteLine(Sku.Normalize("ab-12"));
// ref struct locals in async methods, as long as they don't cross an await.
Console.WriteLine(await Lookup.TrimmedLengthAfterDelayAsync(" ORD-1042 "));
// Partial property: declared by you, implemented by a source generator (here, by hand).
var product = new Product { Name = " Widget " };
Console.WriteLine($"[{product.Name}]");
sealed class DeliveryRoute
{
public string[] Stops { get; } = new string[3];
}
static class Sku
{
[OverloadResolutionPriority(1)]
public static string Normalize(ReadOnlySpan<char> text) => "span: " + text.ToString().ToUpperInvariant();
public static string Normalize(string text) => "string: " + text.ToUpperInvariant();
}
static class Lookup
{
public static async Task<int> TrimmedLengthAfterDelayAsync(string text)
{
await Task.Delay(10);
ReadOnlySpan<char> trimmed = text.AsSpan().Trim();
return trimmed.Length;
}
}
partial class Product
{
public partial string Name { get; set; }
}
partial class Product
{
private string _name = "";
public partial string Name
{
get => _name;
set => _name = value.Trim();
}
}

Output:

14
Customer A -> Customer B -> Depot
span: AB-12
8
[Widget]
  • \e is the ESCAPE character (U+001B), useful for terminal color codes. It replaces \x1b, which was error-prone because following hexadecimal characters became part of the escape.
  • Implicit index access allows the ^ “from the end” operator in object initializers.
  • [OverloadResolutionPriority(n)] tells the compiler to prefer one overload over others with lower priority. It is for library authors who add a better overload, such as a span version, without making existing calls ambiguous. Use it sparingly: it overrides the normal “better conversion” rules.
  • ref locals and ref struct locals in async methods and iterators are allowed when they aren’t used across an await or yield return. Moving the ReadOnlySpan<char> above the await and reading it afterwards produces “CS4007: Instance of type ‘System.ReadOnlySpan’ cannot be preserved across ‘await’ or ‘yield’ boundary.” Iterators may also contain unsafe blocks, but yield return and yield break must be in safe code.
  • Partial properties and indexers have one declaring part (no body) and one implementing part with matching signatures; the implementing part can’t be an auto-property. Source generators are the main users.
  • Method group natural type inference now prunes inapplicable candidates scope by scope, matching overload resolution more closely.
  • The field keyword was available under LangVersion preview; it became a standard feature in C# 14.

From Microsoft’s compiler breaking-change list for .NET 8.0.100 through .NET 9.0.100:

  • Collection expression overload resolution changed. An empty collection expression no longer uses “is it a span” as a tie-breaker, and exact element type matches are preferred. M([]) with M(ReadOnlySpan<int>) and M(Span<object>) overloads compiled in C# 12 and is an error in C# 13.
  • Iterators introduce a safe context. An unsafe class no longer passes its unsafe context into local functions declared inside an iterator; add unsafe to the local function.
  • [InlineArray] on a record struct is an error (CS9259).
  • Method group natural type now reports an ambiguity (CS8917) where the compiler previously inferred a delegate type that depended on declaration order with default or params parameters.
  • params span overloads in .NET 9 libraries can break calls inside expression trees. This is the mechanism behind the C# 14 span-conversion breaks too; the C# 14 page covers that follow-up.
  1. Move off net9.0. Retarget to .NET 10 or .NET 11 (see the support row above); that also raises the default language version, so read the C# 14 and C# 15 breaking changes too.
  2. Rebuild and scan for CS8640 and CS9226 in expression-tree lambdas (common in LINQ providers and mocking setups), and for CS8917 ambiguities.
  3. Convert private object lock fields to Lock where the field is never exposed or used with Monitor.Wait. Treat CS9216 as an error.
  4. Review overloads you own. If you add params ReadOnlySpan<T> to a public API, keep the array overload, consider OverloadResolutionPriority and test expression-tree callers.

Where it sits in the language’s evolution

Section titled “Where it sits in the language’s evolution”

C# 13 is a “plumbing” release. Span<T> (C# 7.2), ref fields and scoped (C# 11), and collection expressions (C# 12) set up span-first APIs; C# 13 lets those spans flow through params, generics, interfaces and async methods. C# 14 then made spans first-class with implicit conversions. Partial properties extend the source generator thread that began with partial methods; C# 14 added partial constructors and events.

What changes when you replace object _gate with Lock _gate in a class that uses lock (_gate)? The compiler emits _gate.EnterScope() and disposes the returned scope instead of calling Monitor.Enter and Monitor.Exit. Nothing else in the code changes, and re-entrancy works as before. If the Lock is ever converted to object, the statement falls back to Monitor, and the compiler warns with CS9216.

Why can a ref struct implement an interface but never be assigned to a variable of that interface type? Converting a struct to an interface boxes it onto the heap. A ref struct must stay on the stack, so boxing would break ref safety. The members are reachable only through a generic type parameter that allows ref structs.

Can you hold a System.Threading.Lock across an await? What does the compiler stop, and what does it miss? No: a Lock is owned by a thread, and the code after an await can resume on a different one. The compiler rejects await inside lock (_gate) (CS1996) and inside using (_gate.EnterScope()), because the Lock.Scope ref struct can’t cross an await (CS4007). Manual Enter(), await, Exit() compiles; in testing, Exit() on the resumed thread threw SynchronizationLockException. Use SemaphoreSlim.WaitAsync for asynchronous mutual exclusion.

Senior scenario: you maintain a shared library targeting .NET Standard 2.0 and .NET 10 and want to add params ReadOnlySpan<T> overloads. What is your plan? Add the span overloads only in the .NET 10 build, behind #if NET9_0_OR_GREATER, and keep the array overloads in every build for binary compatibility. Add tests that compile representative expression-tree callers against the new version, and document the overload change in release notes so consumers know why their code may rebind. Use OverloadResolutionPriority only if a new overload would otherwise be ambiguous.

  • C# 13 is the .NET 9 language version; plan the move to a supported .NET.
  • params works with spans and collection interfaces; span overloads win, which can break expression trees.
  • Typing a lock field as System.Threading.Lock switches lock to the new API with no other code change; keep it typed as Lock.
  • allows ref struct and ref struct interfaces make span-based generic code possible.
  • Partial properties and OverloadResolutionPriority are mainly tools for generator and library authors.