Skip to content

C# 12 (2023): primary constructors and collection expressions

  • What C# 12 added, which SDK and Visual Studio version it needs, and how LangVersion selects it.
  • How primary constructors on ordinary classes differ from record primary constructors, and the capture pitfalls.
  • How collection expressions replace several older initialization styles, and what the compiler creates for each target type.
  • The smaller features: inline arrays, default lambda parameters, ref readonly parameters, alias any type and [Experimental].
  • What to check when moving a .NET 8 codebase forward.

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

Item Value
Released November 2023
Paired runtime .NET 8 (LTS)
Minimum toolset .NET 8 SDK; Visual Studio 2022 version 17.8
Default for TFM net8.0
LangVersion 12.0 (or 12)
Support today Out of support: .NET 8 support ended November 10, 2026. Microsoft supports each language version only on its paired target framework or later
Previews in this release Interceptors (experimental, for source generators)
Feature Weight Mainly for Deep dive
Primary constructors Headline App code (services, DI) Primary constructors
Collection expressions Headline App and library code Collection expressions
Inline arrays Smaller Performance This page
Default lambda parameters Smaller App code This page
ref readonly parameters Smaller Library code This page
Alias any type Smaller App code This page
[Experimental] attribute Smaller Library code This page
Interceptors Preview Source generators This page

Create a console app with dotnet new console, replace Program.cs with the sample, and set <LangVersion>12.0</LangVersion> in the project file when you build with a newer SDK, so the compiler rejects later syntax. The samples use the console template’s implicit using directives and <Nullable>enable</Nullable>, and set the invariant culture so decimals print the same everywhere. They were compiled with the compiler in .NET SDK 10.0.115 using -langversion:12.0 and run on .NET 10.0.15. Output is shown under each sample.

Dependency-injected classes repeat the same three lines for every dependency: a private field, a constructor parameter and an assignment. Records had a concise parameter list since C# 9, but ordinary classes and structs didn’t.

Any class or struct can declare parameters after its name. The parameters are in scope for the entire type body. Unlike records, the compiler creates no public properties. If a member uses a parameter after construction, the compiler stores it in a hidden field. A class with a primary constructor no longer gets an implicit parameterless constructor, and every other constructor must chain to it with this(...).

OrdersPortal’s invoice service takes a clock and a tax rate.

using System.Globalization;
CultureInfo.CurrentCulture = CultureInfo.InvariantCulture; // same output on every machine
var service = new InvoiceService(new FixedClock(new DateTime(2026, 11, 13)), 0.2m);
Console.WriteLine(service.Describe(100m));
var numbers = new OrderNumberGenerator(1000);
numbers.Next();
Console.WriteLine(numbers.Next()); // 1002: 'start' was mutated
public interface IClock { DateTime UtcNow { get; } }
public sealed class FixedClock(DateTime now) : IClock { public DateTime UtcNow => now; }
// Primary constructor on a regular class: parameters are in scope for the whole body.
public sealed class InvoiceService(IClock clock, decimal taxRate)
{
// Validate once and store in a readonly field; don't also use 'taxRate' elsewhere (CS9124).
private readonly decimal _taxRate = taxRate >= 0 ? taxRate : throw new ArgumentOutOfRangeException(nameof(taxRate));
public string Describe(decimal net) =>
$"{clock.UtcNow:yyyy-MM-dd}: net {net:F2}, gross {net * (1 + _taxRate):F2}";
}
// Gotcha: a captured parameter is a mutable hidden field, not a readonly property.
public class OrderNumberGenerator(int start)
{
public int Next() => ++start;
}

Output:

2026-11-13: net 100.00, gross 120.00
1002
  • Captured parameters are mutable. Nothing stops a method from assigning to clock or incrementing start. If you need readonly, assign the parameter to a readonly field and use only the field.
  • Double storage. Using a parameter both to initialize a field and directly in a member stores it twice, and the two copies can drift apart. The compiler warns with CS9124.
  • No validation hook. There is no constructor body. Validate in a field initializer, as _taxRate does, or keep an explicit constructor.

Keep an explicit constructor when construction needs several validation steps, when the type has overloads with different logic, or when a team rule requires readonly dependencies and you don’t want to add fields by hand. For pure data, a record is usually clearer because it also gives you properties and value equality.

C# had a different syntax for arrays (new[] { }), lists (new List<T> { }), spans (stackalloc) and empty collections (Array.Empty<T>()). Combining collections needed Concat and ToArray.

Square brackets create a collection whose type comes from the target: arrays, Span<T> and ReadOnlySpan<T>, types with a collection initializer or a [CollectionBuilder] create method, and the interfaces IEnumerable<T>, IReadOnlyCollection<T>, IReadOnlyList<T>, ICollection<T> and IList<T>. The spread element ..e inlines every element of another collection.

The compiler chooses the storage. For an interface target it picks a concrete type you shouldn’t depend on. The empty expression [] can become Array.Empty<T>() when the target won’t be modified, so it doesn’t allocate, and a span target can be stack-allocated. Unlike a LINQ query, the expression is always evaluated eagerly into an in-memory collection, even when the target is IEnumerable<T>. The IDE rules IDE0300 to IDE0305 offer to convert arrays, empty collections, stackalloc, Create() calls, builders and fluent ToList() chains to collection expressions.

OrdersPortal builds its list of shipping regions and retry delays.

using System.Globalization;
CultureInfo.CurrentCulture = CultureInfo.InvariantCulture;
string[] defaultRegions = ["EU", "US"];
List<string> pilotRegions = ["APAC"];
ReadOnlySpan<int> retryDelaysMs = [100, 200, 400]; // span target: no heap array needed
// Spread (..) inlines the elements of another collection.
string[] shippingRegions = [.. defaultRegions, .. pilotRegions, "LATAM"];
Console.WriteLine(string.Join(",", shippingRegions));
// Interface targets: the compiler picks the concrete type.
IReadOnlyList<string> noDiscounts = [];
Console.WriteLine($"{retryDelaysMs.Length} {noDiscounts.Count} {ReferenceEquals(noDiscounts, Array.Empty<string>())}");
// Arguments work too: the target type comes from the parameter.
Console.WriteLine(OrderMath.Total([19.99m, 5.01m]));
static class OrderMath
{
public static decimal Total(IEnumerable<decimal> lines) => lines.Sum();
}

Output:

EU,US,APAC,LATAM
3 0 True
25.00

The True shows that, with this compiler, [] assigned to IReadOnlyList<string> reused the cached empty array.

  • A target type is required. var regions = ["EU"]; fails with CS9176 (“There is no target type for the collection expression”).
  • Don’t downcast interface results. Casting an IReadOnlyList<T> built from [...] back to List<T> or an array may fail, because the concrete type is the compiler’s choice.
  • No constructor arguments in C# 12. You can’t pass a capacity or a comparer. C# 15 added with(...) for that; until then, keep new HashSet<string>(StringComparer.OrdinalIgnoreCase) { ... }.
  • Overloads can change. An argument such as ['a', 'b'] can now match several overloads; a later compiler update changed one such case (see Breaking changes).

Keep explicit construction when the comparer, capacity or concrete type matters to correctness, and don’t use a collection expression to stand in for a lazy sequence: it materializes every element up front.

[InlineArray(n)] on a struct with exactly one field creates a fixed-size buffer stored inside the struct, which converts to a span. Microsoft notes that most developers consume inline arrays through runtime APIs rather than declare their own; they are a safe alternative to fixed buffers. You can’t initialize one with a collection expression.

using System.Globalization;
using System.Runtime.CompilerServices;
CultureInfo.CurrentCulture = CultureInfo.InvariantCulture;
// OrdersPortal keeps the last four prices of a SKU inline in a struct, without a separate array.
var history = new PriceHistory();
decimal[] incoming = [10.00m, 10.50m, 9.75m, 11.25m, 12.00m];
foreach (decimal price in incoming)
{
history.Record(price);
}
Console.WriteLine(string.Join(" ", history.Recent()));
struct PriceHistory
{
private PriceBuffer _prices; // 4 decimals stored inside the struct
private int _count;
public void Record(decimal price)
{
Span<decimal> prices = _prices; // an inline array converts to a span
if (_count == prices.Length)
{
prices[1..].CopyTo(prices); // drop the oldest
prices[^1] = price;
}
else
{
prices[_count++] = price;
}
}
public readonly decimal[] Recent()
{
ReadOnlySpan<decimal> prices = _prices;
return prices[.._count].ToArray(); // copy out: a span can't escape the struct
}
}
[InlineArray(4)]
struct PriceBuffer
{
private decimal _element0;
}

Output:

10.50 9.75 11.25 12.00

A property that returned a span over _prices directly fails with CS8170 (“Struct members cannot return ‘this’ or other instance members by reference”), which is why Recent() copies.

Default lambda parameters, ref readonly, alias any type and Experimental

Section titled “Default lambda parameters, ref readonly, alias any type and Experimental”
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using Coordinates = (double Lat, double Lon); // alias any type: a named tuple shape
CultureInfo.CurrentCulture = CultureInfo.InvariantCulture;
// Default lambda parameter: shelf labels use the "SKU" prefix unless told otherwise.
var label = (string sku, string prefix = "SKU") => $"{prefix}-{sku}";
Console.WriteLine(label("1042"));
Console.WriteLine(label("1042", "RET"));
// Alias any type: warehouse locations get a domain name instead of a bare tuple.
Coordinates warehouse = (52.37, 4.90);
Console.WriteLine($"{warehouse.Lat},{warehouse.Lon}");
// ref readonly parameter: approval checks read a large order total by reference, never write it.
decimal bigOrderTotal = 12_500m;
Console.WriteLine(Pricing.NeedsApproval(in bigOrderTotal));
// [Experimental]: callers of the new discount engine must opt in explicitly.
#pragma warning disable ORDERS001
Console.WriteLine(Pricing.DynamicDiscount(200m));
#pragma warning restore ORDERS001
static class Pricing
{
public static bool NeedsApproval(ref readonly decimal total) => total > 10_000m;
[Experimental("ORDERS001")]
public static decimal DynamicDiscount(decimal net) => net * 0.05m;
}

Output:

SKU-1042
RET-1042
52.37,4.9
True
10.00
  • Default lambda parameters follow the same rules as method defaults.
  • ref readonly parameters say “pass me a variable, and I won’t modify it”. They suit APIs that used ref without writing, or used in but need a variable rather than a temporary. Microsoft lists changing ref to ref readonly as a compatible change: existing ref call sites compile unchanged, and a non-variable argument only gets warning CS9193. Changing ref to in is on its disallowed list, because the parameter’s modifier is part of the method signature, so callers compiled against the old version break until they are rebuilt. Rebuilt ref call sites still compile, but with warning CS9191 (“The ‘ref’ modifier for argument corresponding to ‘in’ parameter is equivalent to ‘in’”), and in silently accepts temporaries.
  • Alias any type lets using name tuples, arrays and pointer types.
  • [Experimental("ID")] marks an API as experimental. The .NET preview-APIs guidance says the compiler produces an error when you use such an API, while the attribute reference describes it as a warning; in testing, removing the #pragma failed the build with “error ORDERS001: … is for evaluation purposes only and is subject to change or removal in future updates. Suppress this diagnostic to proceed.” Either way, the caller must opt in explicitly.

Interceptors let a source generator replace specific call sites with calls to generated methods. In C# 12 they were an experimental preview that required <InterceptorsPreviewNamespaces> in the project file, and Microsoft didn’t recommend them for production. Treat any C# 12-era interceptor code as tied to a specific compiler version.

C# 12 is additive for most code. Microsoft’s compiler breaking-change list for .NET 7.0.100 through .NET 8.0.100 includes these items you can hit when you recompile:

  • ref arguments can be passed to in parameters with LangVersion 12 or later, a side effect of ref readonly. This relaxes overload resolution and can change which overload binds.
  • Collection expression targets need a usable constructor and Add method (Visual Studio 2022 17.10). A call such as Print(['a', 'b', 'c']) with char[] and string overloads is no longer ambiguous; it binds to char[].
  • Async using prefers a pattern-based DisposeAsync() over an explicit IAsyncDisposable implementation (17.10).
  • Dynamic arguments must use ref modifiers that match the parameter at compile time (17.10); the failure moves from run time to compile time.

Later compilers also tightened the ref-safety rules for collection expressions of span type; that change is explained on the C# 15 page.

  1. Move off net8.0. Retarget to .NET 10 or .NET 11 (see the support row above); changing the target framework also raises the default language version, so read the C# 13 to 15 breaking changes first.
  2. Don’t set LangVersion to latest. Microsoft warns that latest depends on the installed compiler and can differ between machines. Omit LangVersion and let the target framework choose, or pin an explicit number.
  3. Adopt primary constructors deliberately. The IDE0290 refactoring converts constructors automatically. Review each result for mutable captures and CS9124 warnings.
  4. Use collection expressions where the target type is obvious, and keep explicit constructors where capacity or comparers matter.

Where it sits in the language’s evolution

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

C# 9 introduced records with primary constructors; C# 12 extended the syntax to every class and struct. Collection expressions continued the “less ceremony” theme of target-typed new (C# 9) and became the base for params collections in C# 13 and collection expression arguments in C# 15. Inline arrays and ref readonly belong to the performance thread that started with Span<T> in C# 7.2.

How does a primary constructor on a class differ from one on a record? A record generates public init-only properties, value equality and deconstruction from its parameters. A class or struct only puts the parameters in scope; if a member uses one after construction, the compiler stores it in a hidden, mutable field.

Why does var x = [1, 2, 3]; fail to compile? Collection expressions are target-typed. With var there is no target type, so the compiler can’t choose between an array, a list, a span or something else, and reports CS9176.

When would you choose ref readonly over in? When the parameter must be a variable, not a value the compiler can copy into a temporary, and when migrating an existing ref parameter that was never written. ref readonly keeps existing ref call sites compiling without warnings and keeps the by-reference contract; switching to in changes the signature (a binary break for already-compiled callers), turns every rebuilt ref call site into a CS9191 warning, and lets callers pass temporaries.

What does IEnumerable<int> ids = [1, 2, 3]; allocate, and does it behave like a LINQ query? It allocates a compiler-chosen collection holding all three elements; don’t rely on its concrete type. It isn’t lazy: unlike a LINQ query, the elements are evaluated immediately, so a collection expression can’t represent an infinite or deferred sequence.

Senior scenario: your team wants to convert every service class in a large codebase to primary constructors. What guidance do you write? Allow it for simple dependency-holding classes. Require a readonly field when the dependency must not be reassigned, treat CS9124 as an error so a parameter is never stored twice, and keep explicit constructors where validation or overloads exist. Roll it out project by project with IDE0290 at suggestion severity rather than one solution-wide refactoring commit, so reviewers can check each class for mutable captures.

  • C# 12 is the .NET 8 language version; plan the move to a supported .NET.
  • Primary constructors put parameters in scope for the whole type; captured parameters are mutable fields, not properties.
  • Collection expressions unify initialization syntax, need a target type and are always evaluated eagerly.
  • Inline arrays, ref readonly parameters and alias any type are mainly for library and performance code.
  • [Experimental] makes opting in to unstable APIs explicit.