Extension members

suggest change

C# 14 adds a new way to write extensions: an extension block inside a static class. The block names the type you're extending and the receiver once, and everything inside it becomes an extension member:

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

        public int WordCount() =>
            s.Split(' ', StringSplitOptions.RemoveEmptyEntries).Length;
    }
}

IsBlank is an extension property, which classic extension methods couldn't express. You call it as title.IsBlank, without parentheses.

Versions:

The classic syntax still works and isn't deprecated. The rest of the Extension Methods chapter covers it. This article covers what's new.

The examples are .NET 10 / C# 14 file-based programs: save the code as app.cs and run it with dotnet run app.cs. All output comes from real runs.

The basics

string title = "  Extension members in C# 14  ";
Console.WriteLine(title.WordCount());
Console.WriteLine(title.IsBlank);
Console.WriteLine("".IsBlank);
Console.WriteLine(title.Squish());

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

        public int WordCount() =>
            s.Split(' ', StringSplitOptions.RemoveEmptyEntries).Length;

        public string Squish() =>
            string.Join(' ', s.Split(' ', StringSplitOptions.RemoveEmptyEntries));
    }
}
5
False
True
Extension members in C# 14

The parts:

Compare with the classic version of WordCount:

public static int WordCount(this string s) =>
    s.Split(' ', StringSplitOptions.RemoveEmptyEntries).Length;

For one method, the difference is small. With many members for the same type, the block saves you from repeating this string s on every method, and it groups the members visually.

Extension properties

Properties are the main reason to use the new syntax. Before C# 14, an extension for "is this a weekend day?" had to be a method, date.IsWeekend(). Now it can read like the properties the type already has:

using System.Net;

HttpStatusCode[] codes = [HttpStatusCode.OK, HttpStatusCode.NotFound, HttpStatusCode.BadGateway];
foreach (var c in codes)
    Console.WriteLine($"{(int)c} {c}: success={c.IsSuccess}, retry={c.ShouldRetry}");

var d = DateOnly.FromDateTime(new DateTime(2026, 10, 18));
Console.WriteLine($"{d:yyyy-MM-dd} weekend={d.IsWeekend} next workday={d.NextWorkday:yyyy-MM-dd}");

static class Extensions
{
    extension(HttpStatusCode code)
    {
        public bool IsSuccess => (int)code is >= 200 and < 300;
        public bool ShouldRetry => code is HttpStatusCode.RequestTimeout
            or HttpStatusCode.TooManyRequests or >= HttpStatusCode.InternalServerError;
    }

    extension(DateOnly date)
    {
        public bool IsWeekend => date.DayOfWeek is DayOfWeek.Saturday or DayOfWeek.Sunday;

        public DateOnly NextWorkday
        {
            get
            {
                var next = date.AddDays(1);
                while (next.IsWeekend) next = next.AddDays(1);
                return next;
            }
        }
    }
}
200 OK: success=True, retry=False
404 NotFound: success=False, retry=False
502 BadGateway: success=False, retry=True
2026-10-18 weekend=True next workday=2026-10-19

Enums are a good fit: they can't have members of their own, so extension properties are the only way to give HttpStatusCode an IsSuccess property.

NextWorkday uses IsWeekend on another DateOnly. Extension members can call each other like normal members.

No state

An extension can't add data to an object. Auto-properties and fields are not allowed in an extension block:

static class Ext
{
    extension(string s)
    {
        public string Tag { get; set; }
        private int _count;
    }
}
app.cs(5,23): error CS9282: This member is not allowed in an extension block
app.cs(6,21): error CS9282: This member is not allowed in an extension block

Extension properties are computed from the receiver, like methods without parentheses. If you really need to attach data to objects you don't own, store it on the side, for example in a ConditionalWeakTable<TKey, TValue>.

Setters and ref receivers

An extension property can have a setter. For a struct, the receiver is normally a copy, so a setter would modify the copy and the change would be lost. Declare the receiver as ref to work on the caller's variable:

var p = new Point { X = 3, Y = 4 };
Console.WriteLine(p.Length);

p.Length += 5;
Console.WriteLine($"{p.X},{p.Y}");

p.Reset();
Console.WriteLine($"{p.X},{p.Y}");

struct Point { public double X; public double Y; }

static class PointExtensions
{
    extension(ref Point p)
    {
        public double Length
        {
            get => Math.Sqrt(p.X * p.X + p.Y * p.Y);
            set
            {
                var k = value / p.Length;
                p.X *= k;
                p.Y *= k;
            }
        }

        public void Reset() { p.X = 0; p.Y = 0; }
    }
}
5
6,8
0,0

p.Length += 5 calls the getter, then the setter, and both see the same variable p. ref receivers are only allowed for value types (or a type parameter constrained to struct):

error CS9300: The 'ref' receiver parameter of an extension block must be a value type or a generic type constrained to struct.

You can also use in (or ref readonly) to pass a large struct without copying it when the members don't modify it.

Static extension members

If the receiver has no name, the block declares static extension members. They are called on the type, as if the type had declared them:

var empty = Money.Zero;
var price = Money.Parse("19.99 EUR");
Console.WriteLine(empty);
Console.WriteLine(price);
Console.WriteLine(string.Repeat("ab", 3));
Console.WriteLine(TimeSpan.FromWorkDays(2));

record Money(decimal Amount, string Currency);

static class Extensions
{
    extension(Money)
    {
        public static Money Zero => new(0, "EUR");

        public static Money Parse(string text)
        {
            var parts = text.Split(' ');
            return new Money(decimal.Parse(parts[0], System.Globalization.CultureInfo.InvariantCulture), parts[1]);
        }
    }

    extension(string)
    {
        public static string Repeat(string s, int count) =>
            string.Concat(Enumerable.Repeat(s, count));
    }

    extension(TimeSpan)
    {
        public static TimeSpan FromWorkDays(int days) => TimeSpan.FromHours(8 * days);
    }
}
Money { Amount = 0, Currency = EUR }
Money { Amount = 19.99, Currency = EUR }
ababab
16:00:00

This is something classic extensions could never do. Before C# 14, TimeSpan.FromWorkDays had to be TimeSpanHelpers.FromWorkDays, and callers had to know the helper class name.

The members are marked static explicitly. A block with an unnamed receiver can only contain static members:

error CS9303: 'Len': cannot declare instance members in an extension block with an unnamed receiver parameter

A block with a named receiver can contain both kinds. Static members just don't use the receiver.

Calling a member the wrong way gives the same errors as for normal members:

Console.WriteLine("x".Dashes(3));
Console.WriteLine(string.WordCount());

static class Ext
{
    extension(string s) { public int WordCount() => 1; }
    extension(string) { public static string Dashes(int n) => new('-', n); }
}
app.cs(1,19): error CS0176: Member 'Ext.extension(string).Dashes(int)' cannot be accessed with an instance reference; qualify it with a type name instead
app.cs(2,19): error CS0120: An object reference is required for the non-static field, method, or property 'Ext.extension(string).WordCount()'

Extension operators

Operators are static members, so they can be extensions too. This lets you add an operator to a type from another library:

var v = new Vec(1, 2) * 3;
Console.WriteLine(v);

record struct Vec(int X, int Y);

static class VecExtensions
{
    extension(Vec)
    {
        public static Vec operator *(Vec v, int k) => new(v.X * k, v.Y * k);
    }
}
Vec { X = 3, Y = 6 }

The usual operator rules apply: at least one parameter must be the extended type.

Generic extension blocks

The block can have type parameters and constraints. All members share them:

int[] numbers = [3, 1, 4, 1, 5, 9, 2, 6];
List<string> none = [];

Console.WriteLine(numbers.IsEmpty);
Console.WriteLine(none.IsEmpty);
Console.WriteLine(string.Join(", ", numbers.EveryOther()));
Console.WriteLine(numbers.SecondLargest());

var d = new Dictionary<string, int> { ["a"] = 1 };
Console.WriteLine(d.GetOr("a", -1));
Console.WriteLine(d.GetOr("z", -1));

Console.WriteLine(string.Join(",", IEnumerable<int>.Sequence(5)));

static class EnumerableExtensions
{
    extension<T>(IEnumerable<T> source)
    {
        public bool IsEmpty => !source.Any();

        public IEnumerable<T> EveryOther()
        {
            bool take = true;
            foreach (var item in source)
            {
                if (take) yield return item;
                take = !take;
            }
        }
    }

    extension<T>(IEnumerable<T> source) where T : IComparable<T>
    {
        public T SecondLargest() => source.OrderDescending().Skip(1).First();
    }

    extension<TKey, TValue>(IReadOnlyDictionary<TKey, TValue> dict)
    {
        public TValue GetOr(TKey key, TValue fallback) =>
            dict.TryGetValue(key, out var v) ? v : fallback;
    }

    extension(IEnumerable<int>)
    {
        public static IEnumerable<int> Sequence(int count) => Enumerable.Range(1, count);
    }
}
False
True
3, 4, 5, 2
6
1
-1
1,2,3,4,5

Notes:

int[] xs = [1, 2, 3];
Console.WriteLine(string.Join(",", xs.Map(x => x * 10)));
Console.WriteLine(string.Join(",", Ext.Map<int, string>(xs, x => $"<{x}>")));

static class Ext
{
    extension<T>(IEnumerable<T> source)
    {
        public IEnumerable<TResult> Map<TResult>(Func<T, TResult> f)
        {
            foreach (var x in source) yield return f(x);
        }
    }
}
10,20,30
<1>,<2>,<3>

When you call the static form (next section) the block's type parameters come first, then the method's: Ext.Map<int, string>.

Compatibility with classic extension methods

Extension blocks compile to the same static methods you'd write by hand. An instance extension method becomes a static method with the receiver as its first parameter, and a property becomes get_X/set_X methods. Reflection shows it:

using System.Reflection;

string s = "hello world";
Console.WriteLine(s.WordCount());
Console.WriteLine(TextExtensions.WordCount(s));
Console.WriteLine(TextExtensions.get_IsBlank(s));
Console.WriteLine(s.Shout());

foreach (var m in typeof(TextExtensions).GetMethods(BindingFlags.Public | BindingFlags.Static | BindingFlags.DeclaredOnly))
    Console.WriteLine($"{m.ReturnType.Name} {m.Name}({string.Join(", ", m.GetParameters().Select(p => p.ParameterType.Name + " " + p.Name))})");

static class TextExtensions
{
    // classic C# 3 syntax
    public static string Shout(this string s) => s.ToUpperInvariant() + "!";

    extension(string text)
    {
        public bool IsBlank => string.IsNullOrWhiteSpace(text);
        public int WordCount() => text.Split(' ', StringSplitOptions.RemoveEmptyEntries).Length;
    }

    extension(string)
    {
        public static string Dashes(int n) => new string('-', n);
    }
}
2
2
False
HELLO WORLD!
String Shout(String s)
Boolean get_IsBlank(String text)
Int32 WordCount(String text)
String Dashes(Int32 n)

What this means in practice:

Because they're the same thing, a classic method and a block member with the same signature conflict:

Console.WriteLine("abc".Twice());

static class Old { public static string Twice(this string s) => s + s; }
static class New { extension(string s) { public string Twice() => s + s; } }
app.cs(1,25): error CS0121: The call is ambiguous between the following methods or properties: 'Old.Twice(string)' and 'New.extension(string).Twice()'

Resolution rules

Extension members are looked up with the same rules as classic extension methods, extended to properties and static members.

Instance members win. The compiler only looks for extensions when the type itself has no applicable member:

var list = new List<int> { 1, 2, 3 };
Console.WriteLine(list.Count);      // List<int>.Count property
Console.WriteLine(list.Count());    // LINQ's Count() extension method

static class Ext
{
    extension(List<int> l)
    {
        public int Count => -1;
    }
}
3
3

The extension Count property is never used. That also means a library can add a member to a type later and silently replace your extension. Like extension methods, extension members are chosen based on the static type of the expression at compile time (see Extension methods dispatch based on static type), and they don't work with dynamic.

Closer scopes win. Extensions declared in the current namespace are found before extensions brought in by a using directive:

using Library;

namespace App
{
    static class Program
    {
        static void Main()
        {
            Console.WriteLine("hello".Describe());
            Console.WriteLine("hello".Kind);
        }
    }

    static class AppExtensions
    {
        extension(string s) { public string Describe() => $"app: {s}"; }
    }
}

namespace Library
{
    static class LibraryExtensions
    {
        extension(string s)
        {
            public string Describe() => $"library: {s}";
            public string Kind => "text";
        }
    }
}
app: hello
text

Describe exists in both places and the one in App wins. Kind exists only in Library, so lookup continues to the using scope and finds it there.

Same scope, same member: ambiguity. Two extension properties with the same name for the same type in the same scope are an error:

Console.WriteLine("abc".Middle);

static class A { extension(string s) { public char Middle => s[s.Length / 2]; } }
static class B { extension(string s) { public char Middle => s[(s.Length - 1) / 2]; } }
app.cs(1,19): error CS9339: The extension resolution is ambiguous between the following members: 'A.extension(string).Middle' and 'B.extension(string).Middle'

Fix it by importing only one namespace, or by calling the one you want through the static form:

Console.WriteLine(A.get_Middle("abcd"));
Console.WriteLine(B.get_Middle("abcd"));
c
b

Null receivers are allowed. A reference-type receiver can be null, just like with classic extension methods (see Null checking). Make the receiver nullable if the members handle it:

string? missing = null;
Console.WriteLine(missing.IsBlank);
Console.WriteLine(missing.OrEmpty().Length);
Console.WriteLine(missing?.Length2 ?? -1);

static class Ext
{
    extension(string? s)
    {
        public bool IsBlank => string.IsNullOrWhiteSpace(s);
        public string OrEmpty() => s ?? "";
        public int Length2 => s is null ? 0 : s.Length * 2;
    }
}
True
0
-1

missing?.Length2 short-circuits before calling the extension, so the result is -1 from ??, not 0.

What's not supported

In C# 14 an extension block can contain methods, properties and operators, instance or static. It can't contain:

error CS8652: The feature 'extension indexers' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version.

And the containing class must still be static, non-generic and not nested:

error CS9283: Extensions must be declared in a top-level, non-generic, static class

When to use extension members

Use an extension block when:

Keep using classic this methods when the code must compile with C# 13 or earlier. For new code on .NET 10 the block syntax does everything the classic syntax does, and the two produce the same compiled methods, so the choice doesn't affect callers.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents