skip to content

In C# 14, how does an extension block add an IsEmpty property and a static member to IEnumerable<T>, and how does it relate to classic extension methods?

level: seniorimportance: nice to knowfreq 25%

answer

  1. the extension contextual keyword
  2. receiver declared once per block
  3. static-only blocks may omit the name
  4. lowered to static methods, no storage

basics

~20 s

C# 14 lets a static class declare extension(IEnumerable<T> source) { ... } blocks holding extension properties, methods, operators and static members. They compile to static methods, and an instance method in a block matches a classic this method exactly.

solid answer

~40 s

An **extension block** names the receiver once: `extension<T>(IEnumerable<T> source) { public bool IsEmpty { get { ... } } }` lets callers write `scores.IsEmpty`. A **static** extension member such as `public static IEnumerable<T> None => [];` is called as `IEnumerable<string>.None`; a block that holds only static members may leave the receiver unnamed: `extension<T>(IEnumerable<T>)`. The compiler lowers everything to static methods on the enclosing class (`get_IsEmpty<T>(IEnumerable<T>)`, `get_None<T>()`), and an instance extension method in a block produces the same metadata as a classic `this` method, so migrating is binary and source compatible. Lookup is unchanged: an instance member such as `ImmutableArray<T>.IsEmpty` still wins. Blocks add no storage, so auto-properties are rejected (CS9282), as are `init` accessors (CS9304), and static members cannot use the receiver (CS9347).

code

csharp · 35 lines
csharp
#:property PublishAot=false
using System.Reflection;
using Shared.Sequences;

List<int> scores = [];
Console.WriteLine(scores.IsEmpty);                              // instance extension property
Console.WriteLine(IEnumerable<string>.None.IsEmpty);            // static extension property
Console.WriteLine(SequenceExtensions.get_IsEmpty(scores));      // the generated accessor method
foreach (var m in typeof(SequenceExtensions).GetMethods(BindingFlags.Public | BindingFlags.Static))
    Console.WriteLine(m);

namespace Shared.Sequences
{
    public static class SequenceExtensions
    {
        extension<T>(IEnumerable<T> source)
        {
            public bool IsEmpty
            {
                get
                {
                    using var e = source.GetEnumerator();
                    return !e.MoveNext();
                }
            }
        }

        extension<T>(IEnumerable<T>)
        {
            public static IEnumerable<T> None => [];
        }

        public static bool HasAny<T>(this IEnumerable<T> source) => !source.IsEmpty;
    }
}

go deeper

for a junior

Recognise the extension(T receiver) { ... } syntax and that it adds properties and static members, not just methods.

for a middle

Explain the named versus unnamed receiver and how members lower to static methods on the enclosing class.

for a senior

Know the limits the SDK enforces, no storage, no init, no virtual members, and why migrating classic methods is binary compatible.

for a principal

Decide when a shared helper library adopts blocks, weighing readable properties and static factories against the C# 14 requirement.

## Why extension blocks exist Classic **extension methods** (a static method with `this` on its first parameter) can only add instance-style **methods**. Anything that would read better as a property, such as `scores.IsEmpty`, had to be written `scores.IsEmpty()`, and nothing could appear as a static member of the extended type. C# 14 adds **extension blocks**, declared with the contextual keyword `extension` inside a top-level, non-generic static class. A block states the **receiver** once and then declares members as if they were written on the extended type. ## Declaring the members A block with a **named receiver** declares instance extension members; the name is in scope in every instance member: - `extension<T>(IEnumerable<T> source) { public bool IsEmpty { get { ... } } }` gives every sequence an `IsEmpty` property, called `scores.IsEmpty`. - Methods in the same block are written without the receiver parameter: `public bool HasMoreThan(int count) { ... }`. **Static** extension members are reached through the type name. They can sit in a block with a named receiver (they just cannot read it), and a block that holds only static members may leave the receiver unnamed: - `extension<T>(IEnumerable<T>) { public static IEnumerable<T> None => []; }` lets callers write `IEnumerable<string>.None`. A block can also declare **user-defined operators** for the extended type. Type parameters that the receiver uses go on the `extension` declaration; extra ones go on the member. One static class can hold many blocks and classic `this` methods side by side. ## What the compiler generates Extension blocks are a front end over the same machinery as before. The enclosing class gets ordinary static **implementation methods**: 1. An instance extension method becomes a static method whose first parameter is the receiver, marked as an extension method: the same metadata a classic `this` method produces. Callers, and other languages, cannot tell the two forms apart, and converting an existing `this` method into a block is **binary and source compatible**. 2. An extension property becomes static accessor methods, such as `get_IsEmpty<T>(IEnumerable<T> source)`, which you can even call directly in static form. 3. A static extension member becomes a static method with no receiver parameter, such as `get_None<T>()`. Because a call still compiles to a static call, the earlier rules carry over: lookup still requires the namespace to be imported, an **applicable instance member still wins** (`ImmutableArray<int>.IsEmpty` is the type's own property, not the extension), and a null receiver reaches the property body as `null`. ## What the compiler rejects The SDK enforces the fact that a block adds **no storage** to the extended type: | Declaration inside a block | Result | |---|---| | `public int Cached { get; set; }` (an auto-property) | CS9282: This member is not allowed in an extension block | | A property with an `init` accessor | CS9304: cannot declare init-only accessors in an extension block | | An instance member in a block with an unnamed receiver | CS9303: cannot declare instance members ... with an unnamed receiver parameter | | A static member that reads the receiver name | CS9347: Static members cannot access the value of extension parameter | | Two blocks in different imported classes declaring the same property | CS9339 at the call: the extension resolution is ambiguous | The modifiers `virtual`, `override`, `abstract`, `sealed`, `new` and `protected` are not allowed on block members either: an extension member is still a static helper and cannot take part in inheritance. ## Classic methods or blocks | Need | Classic `this` method | Extension block (C# 14) | |---|---|---| | Instance-style method | yes | yes, same metadata | | Extension property | no | yes | | Static member on the extended type | no | yes | | User-defined operator for an existing type | no | yes | | Fields or auto-properties | no | no | For existing helpers there is no urgency to migrate; the call sites compile the same either way. Blocks pay off when several members share one receiver and generic constraints, or when a property or a static factory reads better than a method. ## Version notes - Extension blocks require C# 14, the default language version on .NET 10; an older `LangVersion` does not compile them. - Extension **indexers** are a C# 15 preview feature and are not part of C# 14. - `extension` became a contextual keyword, so a type or alias named `extension` is now an error.

  • Can a team convert its existing this-parameter extension methods into extension blocks without breaking callers?
    Yes. An instance extension method declared in a block compiles to the same static method and metadata as the classic form, so both already-compiled callers and source callers keep working. The conversion is a readability choice, not a compatibility risk.
  • Why can an extension property not be an auto-property or cache a value?
    An extension block adds no fields to the extended type, and an auto-property needs a backing field, so the compiler rejects it with CS9282. Every extension property is computed by its accessors from the receiver and other reachable state.
  • When can an extension block leave its receiver unnamed?
    When it declares only static members, such as `public static IEnumerable<T> None => [];`, which are called through the type and have no receiver value. Static members may also sit in a named block, but reading the receiver from one is CS9347, and an instance member in an unnamed block is CS9303.

  • An extension property can be an auto-property that stores a value per receiver.
  • Extension blocks compile to a new kind of member the runtime attaches to the type.
  • Migrating this-methods into a block breaks already-compiled callers.
  • In C# 14 an extension property overrides an instance property of the same name.
  • Extension indexers shipped in C# 14 with properties.

Assumes C# 14 (.NET 10 SDK); extension blocks, extension properties and static extension members are new in C# 14, and extension indexers are a C# 15 preview.