SharpRuneOpen playground

C# 14 in practice: extension members, field-backed properties and span-aware overloads

How C# 14's extension members, field keyword, null-conditional assignment and span conversions behave in real code, which pitfalls to expect, and how to adopt them on .NET 10.

Conceptual editorial illustration of C# 14 language features: new capabilities attaching to an existing type without changing it. The illustration is conceptual.

Extension members attach new capabilities to existing types without changing them. The illustration is conceptual. · ImageGen illustration

C# 14, a year into .NET 10

C# 14 shipped with .NET 10 in November 2025, a long-term support release patched until November 2028. A year on, .NET 11 became generally available on 10 November 2026 with C# 15 as the default for net11.0 projects, and .NET 8 and .NET 9 left support on the same day. Many teams are therefore meeting C# 14 now, during a migration off .NET 8, which makes it worth examining as working code rather than release notes.

The features are not equally important. Some change API design, some remove boilerplate, and one quietly changes which overloads existing code binds to. This article goes deep on four: extension members, the field keyword, null-conditional assignment and the implicit span conversions, covering what the compiler does, the mistakes each invites and when the older pattern is still better. Compound assignment operators, lambda modifiers, nameof with unbound generics and partial constructors and events get shorter treatment, and the last section is an adoption plan.

References: Microsoft Learn: What's new in C# 14 · .NET support policy

Extension blocks group members by receiver

Classic extension methods mark the first parameter of a static method with this. C# 14 adds a second syntax: inside a top-level, non-generic static class, an extension block names the receiver once and then contains ordinary-looking members. The receiver parameter, text in the example, is in scope in every instance member of the block, and callers use those members as if the receiver type had declared them. In C# 14 a block can hold methods, properties and operators; extension indexers arrived later, in C# 15.

A block whose receiver has no name, such as extension(TimeSpan), may contain only static members, which callers reach through the type, as in TimeSpan.FromWorkingDays(2). That is genuinely new: previously such helpers lived in classes like TimeSpanHelpers that every caller had to discover. The same mechanism allows user-defined operators on types you do not control. For generic receivers, a type parameter used in the receiver belongs on the extension declaration, one used by a single member belongs on that member, and the same parameter cannot be declared in both places.

C# 14 · .NET 10 SDK

C#
using System;
using Shop.Extensions;

string? nickname = "   ";
Console.WriteLine(nickname.IsBlank);             // True
Console.WriteLine(nickname.OrIfBlank("guest"));  // guest
Console.WriteLine(TimeSpan.FromWorkingDays(2));  // 16:00:00

namespace Shop.Extensions
{
    public static class TextAndTimeExtensions
    {
        // Instance extension members: the receiver is named.
        extension(string? text)
        {
            public bool IsBlank => string.IsNullOrWhiteSpace(text);

            public string OrIfBlank(string fallback) =>
                string.IsNullOrWhiteSpace(text) ? fallback : text;
        }

        // Static extension members: the receiver is only a type.
        extension(TimeSpan)
        {
            public static TimeSpan FromWorkingDays(int days) =>
                TimeSpan.FromHours(days * 8);
        }
    }
}

References: Microsoft Learn: What's new in C# 14 · Microsoft Learn: Extension member declarations · C# feature specification: Extension members

An extension property is a computed view, not new state

Extension properties read so naturally that it is easy to forget what they are: static methods that take the receiver as an argument. An extension block cannot declare fields, so an extension property has no storage of its own; its value must be computed from the receiver or fetched from elsewhere. It cannot have an init accessor, and extension members cannot be virtual, abstract, override, protected or readonly. Reaching for a ConditionalWeakTable to give one a backing value is a sign that the design wants a wrapper type or a change to the original type.

There is no implicit receiver: inside a member you write text.Length rather than Length, and text.IsBlank rather than IsBlank. Because the call is static underneath, a null receiver does not throw at the call site. IsBlank deliberately accepts a nullable string, but a reader of customer.Nickname.IsBlank cannot see that null is handled, so declare nullable receivers on purpose and name such members accordingly.

Property syntax also promises cheapness. Microsoft's reference article illustrates extension properties with a Median that sorts the whole sequence on every read; as a method the cost would be visible, but as a property it invites repeated reads in loops and repeated enumeration of lazy sources. Keep extension properties for cheap, stable values and use methods for anything that enumerates, allocates heavily or performs input and output. The compiler also rejects extension property access inside expression trees, so one cannot appear in an Entity Framework Core query predicate.

References: Microsoft Learn: Extension member declarations · C# feature specification: Extension members

How lookup chooses between members and extensions

Lookup follows the rules of classic extension methods. The compiler first looks for an applicable member on the type itself and considers extensions only when none exists. It then searches scope by scope: extensions declared in the closest enclosing namespace, then those imported by using directives at that level, then outer namespaces and finally the compilation unit. All candidates found in one scope compete in a single overload resolution. Extension properties resolve as methods with one parameter, the receiver, and static extension members as if the type were an extra argument.

Two consequences matter. First, a member on the type always wins: if a library you extend later adds its own IsLarge property, every call site rebinds to it on the next build, whatever its meaning, so name extensions in your domain's vocabulary and test the important ones. Second, two namespaces imported at the same level that extend a type with the same member name produce an ambiguity error, as in the example. Fix that at the import, by dropping a using directive the file does not need or by moving one set of extensions to a namespace that only the relevant layer imports.

When a file genuinely needs both, call the implementation directly: each extension member is emitted as an ordinary static method, so a property getter can be called as get_ followed by the property name, with the receiver as its argument. One rough edge remains in C# 14: if an extension method and an extension property share a name and both apply, the compiler reports an ambiguity rather than choosing a member kind.

C# 14 · .NET 10 SDK

C#
using System;
using Shop.Pricing;
using Shop.Reporting;

var order = new Order(250m);

// Both imported namespaces extend Order with IsLarge at the same scope,
// so this line would not compile: the reference is ambiguous.
// Console.WriteLine(order.IsLarge);

// Each extension member is emitted as an ordinary static method, so a file
// that genuinely needs both definitions can call them explicitly.
Console.WriteLine(PricingExtensions.get_IsLarge(order));   // True
Console.WriteLine(ReportingExtensions.get_IsLarge(order)); // False

// If Order later declares its own IsLarge, order.IsLarge binds to that
// member instead: members of the type are always found before extensions.

public sealed record Order(decimal Total);

namespace Shop.Pricing
{
    public static class PricingExtensions
    {
        extension(Order order)
        {
            public bool IsLarge => order.Total >= 100m;
        }
    }
}

namespace Shop.Reporting
{
    public static class ReportingExtensions
    {
        extension(Order order)
        {
            public bool IsLarge => order.Total >= 1_000m;
        }
    }
}

References: Microsoft Learn: Extension member declarations · C# feature specification: Extension members

Migrating classic extension methods, or leaving them alone

Existing extension methods do not need rewriting. The this-parameter form remains fully supported, and Microsoft's reference documentation states that both forms generate the same intermediate language, so converting is binary and source compatible. Both forms can share one static class, so you can add a block for new properties beside existing methods and convert old ones only when you touch them. A documentation comment on the block is copied to every member generated from it.

Compatibility depends on the conversion being exact. The emitted method lists the block's type parameters before the member's own and puts the receiver first in the parameter list, so a classic Map<TResult, TSource>(this IEnumerable<TSource> source) cannot be reproduced; callers passing explicit type arguments would find them reordered. Leave such methods in classic form. A classic method and a block member with the same receiver and signature in one class count as duplicates, so convert rather than copy.

Value-type receivers behave as before: a by-value struct receiver is a copy, so a mutating member needs extension(ref Counter counter). Ref, ref readonly and in receivers require a type known to be a value type, and by-value and by-reference receivers need separate blocks. For library authors, the compiler emits grouping types with content-based names designed to stay stable across recompilation and reordering, which keeps documentation references and public API tracking steady.

References: Microsoft Learn: Extension member declarations · C# feature specification: Extension members

When an extension member is the wrong tool

Microsoft's programming guide keeps its long-standing advice: when you own a type, add the member to the type. Extension members suit types you cannot change, functionality deliberately scoped to one layer, and interfaces where one implementation should serve every implementer, which is how LINQ works. The new syntax makes extensions more pleasant to write, and therefore easier to overuse.

A few patterns deserve suspicion. A widely imported namespace of extension properties on string or object clutters completion lists and hides where each member comes from. Extension properties on domain entities move business rules away from the entity, until two layers compute IsOverdue differently. Static extensions can give a third-party type a factory its authors never designed. Extension operators are the sharpest case, because two codebases can give the same expression different meanings.

References: Microsoft Learn: Extension member declarations

The field keyword removes backing-field ceremony

Before C# 14, adding one line of validation to an auto-property meant declaring a private field, writing both accessors and keeping the names in step. The field contextual keyword gives an accessor body the compiler-synthesized backing field, and an automatic accessor can now sit beside one with a body. The common shapes are normalization in a setter, range checks that throw, change notification in view models and lazy initialization with field ??= and a factory call. Expression-bodied and get-only properties can use field too.

The keyword also tightens encapsulation. A hand-written backing field is visible to the whole class, so any method can bypass the setter; the synthesized field is reachable only from the accessors. That also tells you when not to migrate: if other members legitimately write the storage without running the setter, such as a bulk reset or custom deserialization, keep the explicit field so that the bypass stays visible. Anything that reached the old field by name, such as reflection-based tools or a serializer configured to read fields, will not find it after the change.

C# 14 · .NET 10 SDK

C#
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Runtime.CompilerServices;

public sealed class CustomerViewModel : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler? PropertyChanged;

    // Normalize, skip no-op writes and notify. The initializer writes the
    // backing field directly, so it neither trims nor raises PropertyChanged.
    public string Name
    {
        get;
        set
        {
            var trimmed = value?.Trim() ?? string.Empty;
            if (field == trimmed) return;
            field = trimmed;
            OnPropertyChanged();
        }
    } = string.Empty;

    // Validate in the setter; the getter stays automatic.
    public int DiscountPercent
    {
        get;
        set => field = value is >= 0 and <= 100
            ? value
            : throw new ArgumentOutOfRangeException(nameof(value));
    }

    // Lazy: the getter is null-resilient, so constructors need not set it.
    public IReadOnlyList<string> Tags => field ??= LoadTags();

    private static IReadOnlyList<string> LoadTags() => ["new"];

    private void OnPropertyChanged([CallerMemberName] string? name = null) =>
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
}

References: Microsoft Learn: What's new in C# 14 · C# feature specification: The field contextual keyword

Initializers, nullability and name clashes with field

A property initializer writes the backing field directly without calling the setter, as it always has for auto-properties. In the example the initial empty Name is neither trimmed nor announced through PropertyChanged. If the initial value must pass the setter's rules, assign it in the constructor, where the setter does run.

Nullable analysis understands the common patterns. For a property of non-nullable reference type, the compiler checks whether the getter is null-resilient, meaning it still returns a non-null value while the field holds its default. A lazy getter such as Tags in the example is resilient, so constructors are not asked to initialize it. A plain automatic getter is not, so the familiar constructor warnings apply.

Name clashes are the real migration risk. Inside a property accessor, an unqualified field now means the backing field even if the class has a member called field. The compiler reports warning CS9258 where the meaning changed, and a local named field in an accessor is error CS9272. Use this.field or @field for the existing member, or rename it, and treat CS9258 as an error during the upgrade so that no accessor silently starts using a fresh, empty field. The keyword does not apply in indexers, field-targeted attributes work as they did for auto-properties, and in a struct the field is read-only when the property or the struct is readonly.

References: C# feature specification: The field contextual keyword · Microsoft Learn: C# compiler breaking changes since C# 13

Null-conditional assignment and what it skips

The null-conditional operators can now appear on the left of an assignment. customer?.LastSeen = now assigns only when customer is not null, and customer is evaluated once. The ?[] form works the same way, compound assignment such as += is allowed, a chain such as a?.b?.c = d stops at the first null, and subscribing to an event on a control that may not exist yet is a natural fit.

The detail that matters is evaluation order. The right-hand side runs only when the receiver is not null, so its side effects disappear with the assignment: if computing the value reserves an identifier or writes an audit entry, that work is skipped, with no visual hint in review. Increment and decrement are not allowed, so write += 1. Deconstruction into conditional targets and ref assignment are rejected, and value-type receivers are excluded: a non-nullable struct cannot use ?. at all, and a nullable struct's Value is not an assignable variable. When the result is used as a value, its type is the nullable form of the assigned type.

Use the operator where null genuinely means there is nothing to do, such as an optional collaborator or a disabled cache, and avoid it where null indicates a bug. Replacing a throwing guard with order?.Status = OrderStatus.Shipped turns a loud failure into silent data loss. If the null case deserves a log entry or an exception, keep the if statement.

C# 14 · .NET 10 SDK

C#
using System;
using System.Collections.Generic;

Customer? customer = FindCustomer(7);
Customer? missing = FindCustomer(8);

customer?.LastSeen = DateTimeOffset.UtcNow;  // assigns
missing?.LastSeen = Stamp("missing");        // Stamp is never called
customer?.Notes += " Contacted.";            // compound assignment is allowed
customer?.VisitCount += 1;                   // ++ and -- are not allowed here
customer?.Tags?[0] = "returning";            // element access; stops at the first null

Console.WriteLine($"{customer?.VisitCount} | {customer?.Notes} | {customer?.Tags?[0]}");

static Customer? FindCustomer(int id) => id == 7 ? new Customer() : null;

static DateTimeOffset Stamp(string label)
{
    Console.WriteLine($"computing a timestamp for {label}");
    return DateTimeOffset.UtcNow;
}

public sealed class Customer
{
    public DateTimeOffset LastSeen { get; set; }
    public string Notes { get; set; } = "New customer.";
    public int VisitCount { get; set; }
    public List<string>? Tags { get; set; } = ["new"];
}

References: Microsoft Learn: What's new in C# 14 · C# feature specification: Null-conditional assignment

Implicit span conversions change which overload you call

C# 14 gives spans first-class treatment in the conversion rules. A single-dimensional array converts implicitly to Span<T> and ReadOnlySpan<T>, Span<T> converts to ReadOnlySpan<T>, ReadOnlySpan<T> allows limited covariance between reference element types, and string converts to ReadOnlySpan<char>. These standard implicit conversions take part in overload resolution, generic type inference and extension method receivers, so a library can ship one ReadOnlySpan<T> extension method that applies to arrays and spans alike.

To stop newly applicable overloads from creating ambiguities, a span conversion is preferred when neither candidate matches exactly, and ReadOnlySpan<T> is preferred over Span<T>. Recompiling unchanged code can therefore bind different methods: on net10.0, Contains on an int array binds to MemoryExtensions.Contains rather than Enumerable.Contains. In ordinary in-memory code the result is the same.

Expression trees are where it hurts. The tree now contains a call to a span-based method; Microsoft documents that such trees fail at runtime when compiled with interpretation, and providers expecting Enumerable.Contains will meet MemoryExtensions.Contains instead. Confirm that your LINQ provider version handles the new shape, and where in doubt bind the enumerable overload explicitly, as the example shows.

C# 14 · .NET 10 SDK

C#
using System;
using System.Linq;
using System.Linq.Expressions;

int[] allowed = [3, 7, 11];

// C# 14 on net10.0: binds to MemoryExtensions.Contains through the
// implicit conversion from int[] to ReadOnlySpan<int>.
Console.WriteLine(allowed.Contains(7)); // True

// Inside an expression tree the same call would also bind to the span method:
//     Expression<Func<int[], int, bool>> risky = (a, n) => a.Contains(n);
// Interpreting that tree fails at runtime, and query providers see
// MemoryExtensions.Contains where they used to see Enumerable.Contains.

// Bind the enumerable overload explicitly where trees are interpreted
// or translated.
Expression<Func<int[], int, bool>> viaStatic = (a, n) => Enumerable.Contains(a, n);
Expression<Func<int[], int, bool>> viaEnumerable = (a, n) => a.AsEnumerable().Contains(n);

Console.WriteLine(viaStatic.Compile(preferInterpretation: true)(allowed, 11));    // True
Console.WriteLine(viaEnumerable.Compile(preferInterpretation: true)(allowed, 4)); // False

References: C# feature specification: First-class span types

Upgrade breaks to look for in span-heavy code

Most of the other documented span changes surface as compile errors. Methods with both array and span overloads can become ambiguous, with test assertion libraries a prominent example; calling AsSpan on one argument resolves it, and API authors can use OverloadResolutionPriorityAttribute. Where overloads differ by return type, the ReadOnlySpan<T> preference can pick the read-only version and break an assignment to Span<T>, as with MemoryMarshal.Cast on an array; AsSpan selects the mutable overload again.

Two cases fail at runtime. A covariant array, such as a string array held in an object array variable, used to flow into an IEnumerable<T> overload; if a Span<T> overload now wins, constructing the span throws ArrayTypeMismatchException. And with C# 14 on an older target framework, Reverse on an array binds to MemoryExtensions.Reverse, which reverses in place and returns nothing. .NET 10 adds an array overload of Enumerable.Reverse that takes precedence, and Microsoft calls C# 14 on older targets an unsupported configuration.

After upgrading, search expression lambdas for Contains and other methods that exist in both Enumerable and MemoryExtensions, such as SequenceEqual, and run integration tests that execute real provider queries. Tests that substitute an in-memory LINQ implementation may not reveal a translation failure.

References: C# feature specification: First-class span types · Microsoft Learn: C# compiler breaking changes since C# 13

Compound assignment operators for mutable accumulators

Until C# 14, x += y on a user-defined type meant x = x + y: the static operator returns a new instance, which is assigned back. That suits small immutable values but allocates and copies on every step for large buffers or accumulators. C# 14 lets a type declare instance compound assignment operators, written as public void operator += with one parameter, plus instance increment and decrement. When the target is a variable and such an operator applies, the compiler calls it on the existing instance; otherwise it falls back to the binary operator. A postfix increment whose result is used still uses the static operator, because the old value must survive.

The trap is aliasing. With only a binary operator, a += b rebinds a and leaves other references to the old object untouched. With an instance operator on a class, the object mutates and every alias sees the change, as the ReferenceEquals check shows. Code that keeps a reference to an earlier total can break without a compile error when a library adds the operator, and the compiler does not check that + and += agree.

Reserve the feature for types whose documented contract is mutable accumulation, such as builders, numeric buffers and statistics collectors. A Money type whose += changes shared instances is a correctness bug waiting for the first cache.

C# 14 · .NET 10 SDK

C#
using System;

var totals = new RunningTotals(3);
var alias = totals;

totals += new decimal[] { 10m, 20m, 30m };        // instance operator +=: mutates in place
Console.WriteLine(ReferenceEquals(alias, totals));  // True: the alias sees the change

var sum = totals + new decimal[] { 1m, 1m, 1m };    // static operator +: allocates
Console.WriteLine(ReferenceEquals(sum, totals));    // False

public sealed class RunningTotals(int length)
{
    private readonly decimal[] _values = new decimal[length];

    public static RunningTotals operator +(RunningTotals left, decimal[] right)
    {
        var result = new RunningTotals(left._values.Length);
        for (var i = 0; i < left._values.Length; i++)
            result._values[i] = left._values[i] + right[i];
        return result;
    }

    public void operator +=(decimal[] right)
    {
        for (var i = 0; i < _values.Length; i++)
            _values[i] += right[i];
    }
}

References: C# feature specification: User-defined compound assignment

Smaller conveniences: lambdas, nameof and partial members

Lambdas can now use parameter modifiers without types. Given a delegate with an out parameter, (text, out result) => int.TryParse(text, out result) compiles. Ref, out, in, ref readonly and scoped are allowed; params still needs an explicit type, and a parameter list must be all typed or all untyped. One break came with this: scoped in a lambda parameter list is now always a modifier, so a type named scoped needs the @ escape there.

nameof accepts unbound generic types, so nameof(List<>) produces List and nameof(Dictionary<,>.Count) produces Count. That retires dummy type arguments, which could break when a constraint changed. Partially unbound forms such as Dictionary<int,> remain errors.

Partial instance constructors and partial events join the partial methods, properties and indexers of earlier versions, and they exist mainly for source generators. Each needs exactly one defining and one implementing declaration; only the implementing constructor may have a this or base initializer, and only one part of the type may use primary constructor syntax. A partial event gets no compiler-generated backing field, so the implementation supplies add and remove, and the event can only be used with += and -=, which means a generator must also provide a way to raise it.

C# 14 · .NET 10 SDK

C#
using System;
using System.Collections.Generic;

// Modifiers without types: the delegate supplies string and out int.
TryParse<int> parse = (text, out result) => int.TryParse(text, out result);
Console.WriteLine(parse("42", out var number) ? number : -1); // 42

// nameof with unbound generic types, including member chains.
Console.WriteLine(nameof(List<>));              // List
Console.WriteLine(nameof(Dictionary<,>.Count)); // Count

delegate bool TryParse<T>(string text, out T result);

References: Microsoft Learn: What's new in C# 14 · Microsoft Learn: C# compiler breaking changes since C# 13

Adopting C# 14 deliberately

The language version follows the target framework. A project that targets net10.0 compiles as C# 14 by default, with the .NET 10 SDK or a later one. Microsoft states that a language version newer than the one associated with the target framework is not supported, and warns against LangVersion latest because its meaning changes with whichever compiler is installed. Remove LangVersion overrides, set TargetFramework, and pin the SDK in global.json so that developer machines and CI use the same compiler. A temporary #error version directive shows which compiler and language version a build uses.

Treat the upgrade and feature adoption as separate changes. First move the SDK and target framework without adopting anything. Fix what the compiler reports, including CS9258, span ambiguities and type names such as extension, scoped or partial that now collide with contextual keywords, and run the span checks described above; adding CS9258 to WarningsAsErrors is cheap insurance. Only then adopt new features, so that any behavior change has a single cause.

Then write a short convention per feature into the team's guidelines. Extension members: methods by default, properties only for cheap values without side effects, purpose-named namespaces, and a review justification for extension operators or extensions on object, string and primitive types. The field keyword: validation, normalization, notification and lazy values, with explicit fields kept where other members must bypass the setter. Null-conditional assignment: only where null means nothing to do. Compound assignment operators: only on documented mutable types. Encode what analyzers and .editorconfig can check, and leave judgment calls to review.

C# 15 is now available for net11.0 projects, adding union types, closed hierarchies and extension indexers among other features. .NET 11 is a standard-term support release that, like .NET 10, is supported until November 2028, so the choice is mostly about upgrade cadence. Either way, the habit of checking lookup rules, evaluation order and overload binding before trusting new syntax carries straight over.

References: Microsoft Learn: Configure the C# language version · .NET support policy · Microsoft Learn: C# compiler breaking changes since C# 13

Continue with SharpRune

Sources & further reading

Technical references checked against primary documentation. Code samples in this article target C# 14 · .NET 10 SDK; in the browser playground, choose .NET 10 or 11 in Settings.

Illustration created with ImageGen for SharpRune. Article and examples are educational; validate behavior in your target runtime.
Put an idea into practice