Best of C# 14 - extension members

We've had extension methods in C# for a long time, but what are Extension Members?

.NET

Extension methods were introduced way back in 2007 with C# 3. But they only allowed you to add methods to an instance type. Extension Members, a new feature of C# 14, finally ‘extend’ this concept to properties and static members too.

C# logo

The classic extension method definition looks like this:

public static class MyExtensions
{
    public static int WordCount(this string str) =>
        str.Split([' ', '.', '?'], StringSplitOptions.RemoveEmptyEntries).Length;
}

The class needed to be static, and the static method’s first parameter needs the this modifier.

That style of extension method hasn’t gone away, and you’re free to keep doing it that way if you like.

But now we can create extension properties or extension methods on types. To do that there’s a new extension keyword that is used to create extension blocks. You can use these for extension properties, and extension methods, and also for both of these for types in addition to instances.

public static class Enumerable
{
    // Extension block
    extension(string str) // extension members for string instances
    {
        // Extension method:
        public int WordCount() =>
            str.Split([' ', '.', '?'], StringSplitOptions.RemoveEmptyEntries).Length;

        // Extension property:
        public bool Is80CharsLong =>
            str.Length == 80;
    }    

    extension(string)
    {
        // extension method
        public static string ToTitleCase(string str) =>
            System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToTitleCase(str);

        // extension property
        public static string TwoSpaces => "  ";
    }
}

You use these extension members like this:

var sentence = "This is a sentence of words.";

int wordCount = sentence.WordCount();

var is80CharsLong = sentence.Is80CharsLong;

var title = string.ToTitleCase("hello world");

var indent = string.TwoSpaces;

It’s another useful language tool. Used appropriately it could make your codebase easier to understand and allow you to separate concerns.

Possible reasons for not using an extension block