Mastering Extension Members in C# 14 — Beyond Extension Methods

C# 14 introduces a powerful enhancement to the concept of extension methods: extension members. This feature allows you to extend not just instance methods, but also properties, indexers, and even static members of a type — with cleaner, more expressive syntax. In this post, we’ll explore: What extension members are How to declare and use them The difference between instance and static extension members A real-world example When and why to use them Motivation — From Extension Methods to Extension Members Before C# 14, we could only extend types with methods using static classes: public static class StringExtensions { public static bool IsNullOrWhiteSpace(this string str) => string.IsNullOrWhiteSpace(str); } Useful? Yes. But limiting — no properties, no indexers, no static-style access. C# 14 changes that with a new syntax: extension(). Syntax Breakdown Here’s the new structure in C# 14: public static class Enumerable { extension(IEnumerable source) { // Instance-like extension members here } extension(IEnumerable) { // Static-like extension members here } } Now let’s walk through a complete example

May 6, 2025 - 22:15
 0
Mastering Extension Members in C# 14 — Beyond Extension Methods

MasteringExtensionMembersInCSharp14

C# 14 introduces a powerful enhancement to the concept of extension methods: extension members. This feature allows you to extend not just instance methods, but also properties, indexers, and even static members of a type — with cleaner, more expressive syntax.

In this post, we’ll explore:

  • What extension members are
  • How to declare and use them
  • The difference between instance and static extension members
  • A real-world example
  • When and why to use them

Motivation — From Extension Methods to Extension Members

Before C# 14, we could only extend types with methods using static classes:

public static class StringExtensions
{
    public static bool IsNullOrWhiteSpace(this string str)
        => string.IsNullOrWhiteSpace(str);
}

Useful? Yes. But limiting — no properties, no indexers, no static-style access. C# 14 changes that with a new syntax: extension<>().

Syntax Breakdown

Here’s the new structure in C# 14:

public static class Enumerable
{
    extension<TSource>(IEnumerable<TSource> source)
    {
        // Instance-like extension members here
    }

    extension<TSource>(IEnumerable<TSource>)
    {
        // Static-like extension members here
    }
}

Now let’s walk through a complete example